144. Binary Tree Preorder Traversal - Medium
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
M1: recursive
time: O(n), space: O(height)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); preorder(root, res); return res; } public void preorder(TreeNode root, List<Integer> res) { if(root == null) { return; } res.add(root.val); preorder(root.left, res); preorder(root.right, res); } }
M2: iterative
time: O(n), space: O(n) -- depending on the tree structure, could keep up to the entire tree
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); LinkedList<TreeNode> s = new LinkedList<>(); if(root == null) { return res; } s.offerFirst(root); while(!s.isEmpty()) { TreeNode cur = s.pollFirst(); res.add(cur.val); if(cur.right != null) { s.offerFirst(cur.right); } if(cur.left != null) { s.offerFirst(cur.left); } } return res; } }