LeetCode145:二叉树的后序遍历(栈与递归)

二叉树的后序遍历

给定一个二叉树,返回它的 后序 遍历。
在这里插入图片描述

List<Integer> retList = new ArrayList<>();
   /**
     * 二叉树的后序遍历:递归
     * @param root
     * @return
     */
    public List<Integer> postorderTraversal(TreeNode root) {
        if(root != null){
            postorderTraversal(root.left);
            postorderTraversal(root.right);
            retList.add(root.val);
        }
         return retList;
    }

进阶:

public List<Integer> postorderTraversal(TreeNode root) {
  List<Integer> ret = new ArrayList<Integer>();
        if(root == null){
            return ret;
        }

        Stack<Pair<TreeNode,Boolean>> stack = new Stack<Pair<TreeNode, Boolean>>();
        stack.push(new Pair<TreeNode, Boolean>(root,false));
        while (!stack.empty()){
            Pair<TreeNode,Boolean> p = stack.pop();
            if(p.getValue().equals(true)){
                ret.add(p.getKey().val);
            }else {
                stack.add(new Pair<TreeNode, Boolean>(p.getKey(),true));
                if(p.getKey().right != null){
                    stack.push(new Pair<TreeNode, Boolean>(p.getKey().right,false));

                }
                if(p.getKey().left != null){
                    stack.add(new Pair<TreeNode, Boolean>(p.getKey().left,false));
                }
            }

        }
        return ret;
    }
    /**
     * 二叉树的后序遍历:非递归(栈)模拟系统指令
     * @param root
     * @return
     */
 public class Command{
        String s;//go,print
        TreeNode node;
        Command(String s,TreeNode node){this.s = s;this.node= node;}
    }
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> retList = new ArrayList<>();
        if(root == null){
            return retList;
        }
        Stack<Command> stack = new Stack<>();
        //入栈
        stack.push(new Command("go",root));
        while (! stack.empty()){
            //将栈顶元素推出
            Command command = stack.pop();
            if(command.s == "print"){
                retList.add(command.node.val);
            }else{
                stack.push(new Command("print",command.node));
                //command.s == "go"
                if(command.node.right !=null){
                    //先右孩子入栈
                    stack.push(new Command("go",command.node.right));
                }
                if(command.node.left != null){
                    //再左孩子入栈
                    stack.push(new Command("go",command.node.left));
                }
             
            }
        }

        return retList;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值