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 }
  • 相关阅读:
    Delphi TWebBrowser[11] 读写html代码
    Nginx 配置反向代理
    清除git中缓存的凭证(用户名及密码)
    python 摄像头
    a 链接控制打开新窗口 无地址栏
    树形多级菜单数据源嵌套结构与扁平结构互转
    使用 git 的正确姿势
    JavaScript this
    JavaScript Scope Chain
    JavaScript Scope Context
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6604230.html
Copyright © 2011-2022 走看看