zoukankan      html  css  js  c++  java
  • LeetCode: 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 ArrayList<Integer> postorderTraversal(TreeNode root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            ArrayList<Integer> result = new ArrayList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            if(root == null) return result ;
            stack.push(root);
            TreeNode prev = null;
            while(!stack.isEmpty()){
               TreeNode curr = stack.peek();
               // traverse down
               if(prev == null || curr == prev.left || curr == prev.right){
                   if(curr.left != null) stack.push(curr.left);
                   else if(curr.right != null) stack.push(curr.right);
               }// traverse up
               else if(curr.left == prev){
                   if(curr.right != null) stack.push(curr.right);
               }else{
                   result.add(curr.val);
                   stack.pop();
               }
               prev = curr;
            }
            return result;
        }
    }
  • 相关阅读:
    [转]线程同步
    [转]C#线程同步(1)- 临界区&Lock
    获取系统空闲时间
    [转]一分钟明白 VS manifest 原理
    泛型总结
    wpf listbox touch 整个窗口移动
    git问题 next fetch will store in remotes/origin
    创建maven项目出现的问题
    JPA
    JDK JRE JVM
  • 原文地址:https://www.cnblogs.com/yeek/p/3486150.html
Copyright © 2011-2022 走看看