public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList();
Stack<TreeNode> stack = new Stack();
if (root == null){
return list;
}
stack.push(root);
while (!stack.isEmpty()){
TreeNode temp = stack.pop();
list.add(temp.val);
if (temp.right!=null){
stack.push(temp.right);
}
if (temp.left!=null){
stack.push(temp.left);
}
}
return list;
}
}
准备一个堆栈stack,一个列表存放结果。
根节点入栈,弹出栈顶,输出到结果列表,右左节点入栈,循环直到堆栈为空。
先序遍历就是根左右,因此入栈时要先右后左。