Question
Given the root
of a binary tree, return the preorder traversal of its nodes’ values.
Example 1:
1 2
| Input: root = [1,null,2,3] Output: [1,2,3]
|
Example 2:
1 2
| Input: root = [] Output: []
|
Example 3:
1 2
| Input: root = [1] Output: [1]
|
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); if(root != null) stack.push(root); while(!stack.isEmpty()){ root = stack.pop(); res.add(root.val); if(root.right != null) stack.push(root.right); if(root.left != null) stack.push(root.left); } return res; } }
|
Complexity:
Time complexity: O(n)
Space complexity: O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); helper(root, res); return res; } private void helper(TreeNode root, List<Integer> res) { if (root == null) return; res.add(root.val); helper(root.left, res); helper(root.right, res); } }
|
Complexity:
Time complexity: O(n)
Space complexity: O(n)