zoukankan      html  css  js  c++  java
  • 145. Binary Tree Postorder Traversal QuestionEditorial Solution

    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?

    每次都先push right, 然后left。 但是需要一个sentinel存每次上一次pop的node, 如果这个node是新的peek的值的子数的话,不能再push到stack,需要进入输出逻辑。 同样进入输出逻辑的还有leaf。

        public IList<int> PostorderTraversal(TreeNode root) {
            var res = new List<int>();
            var stack = new Stack<TreeNode>();
            if(root == null) return res;
            stack.Push(root);
            var rightPointer = new TreeNode(-1);
            while(stack.Count() > 0)
            {
                if((root.right == null && root.left == null)||(root.left == rightPointer ) || (root.right == rightPointer) )
                {
                    res.Add(root.val);
                    rightPointer = stack.Pop();
                    if(stack.Count()>0)
                    root = stack.Peek();
                }
                else
                {
                    if(root.right != null) stack.Push(root.right);
                    if(root.left != null) stack.Push(root.left);
                    root = stack.Peek();
                }
                
            }
            return res;
        }
  • 相关阅读:
    硬件设计问题——持续更新
    PCB设计资源整理
    PCB层叠设计和电源分割
    PCB设计技巧
    铜厚电流、Layout 3W原则 20H原则 五五原则
    final关键字
    面向对象——继承与组合
    面向对象——继承
    this总结
    static总结
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5860920.html
Copyright © 2011-2022 走看看