二叉树的遍历

//144. Binary Tree Preorder Traversal (Medium)
    public List<Integer> preorderTraversal(TreeNode root){
        List<Integer> ret = new ArrayList<Integer>();
        if(root==null){
            return ret;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            ret.add(node.value);
            if(node.right!=null){
                stack.add(node.right);
            }
            if(node.left!=null){
                stack.add(node.right);
            }
        }
        return ret;
    }
    
    //145. Binary Tree Postorder Traversal (Medium)
    //前序遍历为 root -> left -> right,后序遍历为 left -> right -> root。可以修改前序遍历成为 root -> right -> left,那么这个顺序就和后序遍历正好相反。
    public List<Integer> postorderTraversal(TreeNode root){
        List<Integer> ret = new ArrayList<Integer>();
        if(root==null){
            return ret;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            ret.add(node.value);
            if(root.left!=null){
                stack.push(node.left);
            }
            if(root.right!=null){
                stack.push(node.right);
            }
        }
        Collections.reverse(ret);
        return ret;
    }
    //94. Binary Tree Inorder Traversal (Medium)
    public List<Integer> inorderTraversal(TreeNode root){
        List<Integer> ret = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode curr = root;
        while(curr!=null || !stack.isEmpty()){
            while(curr!=null){
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            ret.add(curr.value);
            curr = curr.right;
        }
        return ret;
    }

 

posted @ 2020-08-06 15:02  helloworldmybokeyuan  阅读(129)  评论(0编辑  收藏  举报