Binary Tree Postorder Traversal

本文介绍了一种不使用递归实现二叉树后序遍历的方法,通过自定义栈节点记录遍历方向,实现了节点的正确访问顺序。

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

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

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

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        Stack<StackNode> stack = new Stack<StackNode>();
        List<Integer> list = new ArrayList<Integer>();
        while(root != null){
            while(root.left != null){
                StackNode stackNode = new StackNode(root,0);
                stack.push(stackNode);
                root = root.left;
            }
            if(root.right != null){
                StackNode stackNode = new StackNode(root,1);
                stack.push(stackNode);
                root = root.right;
            }else{//叶子节点
                list.add(root.val);
                while(!stack.empty()){
                    StackNode node = stack.peek();//返回栈顶元素
                    if(node.flag == 1){//访问过右子树
                        node = stack.pop();
                        list.add(node.t.val);
                    }else{//访问完左子树
                        if(node.t.right != null){//有右子树
                            node.flag = 1;
                            root = node.t.right;
                            break;
                        }else{//没有右子树
                            list.add(node.t.val);
                            stack.pop();
                        }
                    }
                }
            }
            if(stack.empty()){
                break;
            }
        }
        return list;
    }
    public class StackNode{
        TreeNode t;
        int flag;//标志遍历的是左边还是右边,如果是遍历完右子树,就退栈,0标志正在遍历左子树,1标志正在遍历右子树
        public StackNode(TreeNode p,int f){
            t = p;
            flag = f;
        }
    } 
}

Runtime: 360 ms

这个题关键是需要记录下遍历的方向(左子树还是右子树,从而来确定父节点是否退栈),这个与迭代的前序和中序不同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值