zoukankan      html  css  js  c++  java
  • 145. 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?

    本题其实和Binary Tree Inorder Traversal比较类似的,只不过是相反的,本题不可以按照正常的顺序来做,因为左子树然后右子树是比较难以转换的,因此可以采用倒着来,即先当前节点,然后是其右子树,做法和之前的中序是一样的,只不过是相反的思路,最后遍历完,把链表list反转过来,代码如下:

     1 /**
     2  * Definition for a binary tree node.
     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         TreeNode node = root;
    14         Stack<TreeNode> stack = new Stack<TreeNode>();
    15         while(!stack.isEmpty()||node!=null){
    16             if(node!=null){
    17                 stack.push(node);
    18                 res.add(node.val);
    19                 node = node.right;
    20             }else{
    21                 node = stack.pop().left;
    22             }
    23         }
    24         Collections.reverse(res);
    25         return res;
    26     }
    27 }
  • 相关阅读:
    图表插件echars的使用案例
    安装Eclipse
    ef 更新数据库
    webapi Route 特性
    WebSite下创建webapi
    C# 泛型约束
    Session共享
    ubuntu eclipse 无法打开
    C# TreeView 连续点击 不触发AfterCheck事件
    ef 仓储模式 Redis
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6604230.html
Copyright © 2011-2022 走看看