题目
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?
方法
private Stack<TreeNode> stack = new Stack<TreeNode>();
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> al = new ArrayList<Integer>();
if (root != null) {
stack.push(root);
while (stack.size() != 0) {
TreeNode node = stack.pop();;
al.add(node.val);
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
}
return al;
}