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;
        }
    }
  • 相关阅读:
    AMD64 Instruction-Level Debugging With dbx
    Solaris 10上安装Oracle 11g
    Dave-oracle
    SSD 下的 MySQL IO 优化
    vmware 网络工作方式
    PLSQL Developer 配置Oralce11g连接 转
    LINUX下的21个特殊符号 转
    linux 内核调试相关资料
    mysql 源代码编绎
    Windows Performance Toolkit
  • 原文地址:https://www.cnblogs.com/yeek/p/3486150.html
Copyright © 2011-2022 走看看