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]
.
思路:普通递归的先序遍历就就不写了,下面给出一种非递归的先序遍历,用stack来实现
public static void preorder(List<Integer> list, TreeNode root) {
if (root == null)
return;
Stack<TreeNode> stack = new Stack<TreeNode>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
list.add(root.val);
stack.push(root);
root = root.left;
}
root=stack.pop();
root=root.right;
}
}