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 }

 

posted @ 2017-03-23 11:32  CodesKiller  阅读(126)  评论(0编辑  收藏  举报