题目来源:二叉树的前序遍历
题目描述:
给出一棵二叉树 {1,#,2,3},
1
\
2
/
3
返回 [1,2,3].
Java代码
public ArrayList<Integer> preorderTraversal(TreeNode root) {
// write your code here
ArrayList<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> s = new Stack<TreeNode>();
while (root!=null||!s.empty()) {
while (root!=null) {
result.add(root.val);
s.push(root);
root = root.left;
}
if (!s.empty()) {
root = s.lastElement();
s.pop();
root = root.right;
}
}
return result;
}