ID | Title | Difficulty | |
---|---|---|---|
Loading... |
144. Binary Tree Preorder Traversal
Easy
LeetCode
Stack, Tree, Depth-First Search, Binary Tree
Problem
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?
Code
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
helper(res, root);
return res;
}
private void helper(List<Integer> res, TreeNode root){
if(root == null) return;
res.add(root.val);
helper(res, root.left);
helper(res, root.right);
}
}
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
if(cur.right != null) stack.push(cur.right);
if(cur.left != null) stack.push(cur.left);
res.add(cur.val);
}
return res;
}
}
按 <- 键看上一题!
143. Reorder List
按 -> 键看下一题!
145. Binary Tree Postorder Traversal