145. Binary Tree Postorder Traversal

Posted CodesKiller

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 

以上是关于145. Binary Tree Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 145. Binary Tree Postorder Traversal

145. Binary Tree Postorder Traversal

LeetCode145. Binary Tree Postorder Traversal 解题报告

145. Binary Tree Postorder Traversal

145. Binary Tree Postorder Traversal

145. Binary Tree Postorder Traversal