145. Binary Tree Postorder Traversal(非递归实现二叉树的后序遍历)

Given a binary tree, return the postorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively? 

方法一:递归

class Solution {
    public void preorderTraversal(TreeNode root) {
        if(root==null) return ;
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        System.out.print(root.val+' ');
    }
}

方法二:用两个栈实现

根据根结点将左右孩子加入栈中这种操作程序比较好实现。用一个栈做中转,另一栈存最终结果的逆序数。

/**
 * 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> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack1=new Stack<TreeNode>();
        Stack<TreeNode> stack2=new Stack<TreeNode>();
        List<Integer> list=new ArrayList<Integer>();
        if(root==null) return list;
        stack1.push(root);
        while (!stack1.isEmpty()){
            root=stack1.pop();
            stack2.push(root);
            if(root.left!=null)
                stack1.push(root.left);
            if(root.right!=null)
                stack1.push(root.right);
        }
        while (!stack2.isEmpty()){
            list.add(stack2.pop().val);
        }
        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> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack=new Stack<TreeNode>();
        List<Integer> list=new ArrayList<Integer>();
        if(root==null) return list;
        TreeNode c=null;
        stack.push(root);
        while (!stack.isEmpty()){
            c=stack.peek();
            if(c.left!=null&&c.left!=root&&c.right!=root){
                stack.push(c.left);
            }else if(c.right!=null&&c.right!=root){
                stack.push(c.right);
            }else { 
                list.add(stack.pop().val);
                root=c;
            }
        }
        return list;
    }
}

 

posted on 2019-04-08 16:10  shaer  阅读(140)  评论(0编辑  收藏  举报

导航