前序遍历(递归与非递归)

非递归

public class Solution {
    /**
     * @param root: A Tree
     * @return: Preorder in ArrayList which contains node values.
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        List<Integer> list = new LinkedList<>();
        if(root==null){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        while (node!=null||!stack.isEmpty()){
            while (node!=null){
                stack.push(node);
                list.add(node.val);
                node=node.left;
            }
            if(!stack.isEmpty()){
                node = stack.pop();
                if(node.right!=null){
                    node=node.right;
                }else {
                    node=null;
                }
            }
        }
        return list;
    }
    
}

递归

    public List<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        List<Integer> list = new LinkedList<>();
        if(root==null){
            return list;
        }
        preorderTraversalCore(root,list);
        return list;
    }
    public void preorderTraversalCore(TreeNode root,List<Integer> list){
           if(root==null){
               return;
           }
           list.add(root.val);
           preorderTraversalCore(root.left,list);
           preorderTraversalCore(root.right,list);
    }
posted @ 2018-03-28 21:28  baixiaoshuai  阅读(256)  评论(0编辑  收藏  举报