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?

    Solution:

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<Integer> postorderTraversal(TreeNode root) {
    12         List<Integer> res = new ArrayList<Integer>();
    13         if (root==null) return res;
    14 
    15         Stack<TreeNode> nStack = new Stack<TreeNode>();
    16         Stack<Integer> record = new Stack<Integer>();
    17         nStack.push(root);
    18         record.push(0);
    19 
    20         while (nStack.size()!=0){
    21             TreeNode cur = nStack.peek();
    22             if (cur.left==null && cur.right==null){
    23                 res.add(cur.val);
    24                 nStack.pop();
    25                 record.pop();
    26                 continue;
    27             }
    28 
    29             int val = record.peek();
    30             if (val==0){
    31                 record.pop();
    32                 record.push(val+1);
    33                 if (cur.left!=null){
    34                     nStack.push(cur.left);
    35                     record.push(0);
    36                 }
    37                 continue;
    38             }
    39 
    40             if (val==1){
    41                 record.pop();
    42                 record.push(val+1);
    43                 if (cur.right!=null){
    44                     nStack.push(cur.right);
    45                     record.push(0);
    46                 }
    47                 continue;
    48             }
    49 
    50             if (val==2){
    51                 res.add(cur.val);
    52                 nStack.pop();
    53                 record.pop();
    54                 continue;
    55             }
    56         }
    57 
    58         return res;  
    59         
    60     }
    61 }
  • 相关阅读:
    P1121 环状最大两段子段和
    无题
    cdoj 1485 柱爷搞子串 sam treap
    自然数幂和
    Gym 100341C AVL Trees NTT
    线性筛分解质因子
    codeforces 366 Ant Man dp
    UVALive 6914 Maze Mayhem 轮廓线dp
    hdu 5790 Prefix 字典树 主席树
    莫比乌斯反演个人小结
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4158857.html
Copyright © 2011-2022 走看看