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]
.
This problem is simple, we just need a stack to help us control the visit order to implement this.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
Stack buffer = new Stack<TreeNode>();
if (root == null) {
return result;
}
buffer.add(root);
while (!buffer.isEmpty()) {
TreeNode cur = (TreeNode) buffer.pop();
result.add(cur.val);
if (cur.right != null) {
buffer.push(cur.right);
}
if (cur.left != null) {
buffer.push(cur.left);
}
}
return result;
}
}