递归方法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> rev = new ArrayList<Integer>();
preorder(root,rev);
return rev;
}
public void preorder(TreeNode root,List<Integer> list)
{
if(root!=null)
{
list.add(root.val);
preorder(root.left,list);
preorder(root.right,list);
}
}
}
非递归方法:
深度优先搜索,遍历时先右孩子入栈,在左孩子入栈;这样在出栈时可以满足NLR的顺序;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> rev = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p;
if(root==null) return rev;
else
{
stack.push(root);
while(!stack.empty())
{
p = stack.pop();
rev.add(p.val);
//注意这里的入栈顺序,必须是先右后左,才能满足出栈访问时先左后右
if(p.right!=null) stack.push(p.right);
if(p.left!=null) stack.push(p.left);
}
}
return rev;
}
}