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?
Check the coding below in detail
/*
Key to solve: stack
Preorder Mid -> Left -> Right
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> out =new ArrayList<Integer>();
if(root==null) return out;
Stack<TreeNode> stack=new Stack<TreeNode>();
//push root into stack first because Preorder start from mid
stack.push(root);
while(!stack.isEmpty()){
root=stack.pop();
out.add(root.val);
if(root.right!=null) stack.push(root.right);
//base on LIFO, the left node will be add into list first
if(root.left!=null) stack.push(root.left);
}
return out;
}
}