递归方法:
/**
* 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) {
if(root == null) return new ArrayList<Integer>();
List<Integer> list = new ArrayList<Integer>();
preorderTraversal(root, list);
return list;
}
public List<Integer> preorderTraversal(TreeNode root, List<Integer> list) {
list.add(root.val);
if(root.left != null)
preorderTraversal(root.left, list);
if(root.right != null)
preorderTraversal(root.right, list);
return list;
}
}
非递归方法:
/**
* 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> res = new ArrayList<Integer>();
if(root==null)
return res;
Stack<TreeNode> stack = new Stack<>();
TreeNode p = root;
//边遍历边打印,并存入栈中,以后需要借助这些节点进入右子树
while(!stack.isEmpty() || p!=null ){
while(p!=null){
res.add(p.val); //先访问,与中序不同
stack.push(p);
p=p.left;
}
if(!stack.isEmpty()){
p = stack.pop();
p=p.right;
}
}
return res;
}
}
非递归第二种方法:(我个人更喜欢这种写法,比较好想,方便记忆)
因为前序是根左右的访问顺序,所以利用一个栈,从根节点开始,访问该节点,然后按照右左子树节点的顺序入栈,注意是右左!因为用的是栈,先进后出,这样下一个访问的节点就是左子树节点啦~
/**
* 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> res = new ArrayList<>();
if(root!=null){
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode p = stack.pop();
res.add(p.val);
if(p.right!=null)
stack.push(p.right);
if(p.left!=null)
stack.push(p.left);
}
}
return res;
}
}
网友评论