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 }
  • 相关阅读:
    initializer_list形参
    前置递增运算符和后置递增运算符的区别
    基本的TCP socket API
    C++ find()函数
    python-对目录下的文件按时间排序
    js常用方法
    selenium中的对文本进行全选,复制,粘贴,剪切和删除的操作
    python 打包exe 命令及去除 cmd框
    mysql命令行修改密码
    html文件转换成excel
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4158857.html
Copyright © 2011-2022 走看看