Given a binary tree, return the preorder traversal of its nodes’ values.
For example: Given binary tree {1,#,2,3},
1
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
Solution 1: recursive
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
preorderTraversal(root, ans);
return ans;
}
public void preorderTraversal(TreeNode root, List<Integer> list) {
if(root==null) return;
list.add(root.val);
preorderTraversal(root.left, list);
preorderTraversal(root.right, list);
}
}
Solution 2: iterative
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
Stack<TreeNode> st = new Stack<>();
while(root!=null || !st.isEmpty()){
while(root!=null){
ans.add(root.val);
st.push(root);
root = root.left;
}
root = st.pop().right;
}
return ans;
}
}