145. Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?

 

 

非递归实现二叉树的后序遍历

 

java:

 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 class Solution {
11     public List<Integer> postorderTraversal(TreeNode root) {
12         List<Integer> res = new ArrayList<Integer>() ;
13         Stack<TreeNode> stack = new Stack<TreeNode>() ;
14         stack.push(root) ;
15         while(!stack.isEmpty()){
16             TreeNode node = stack.pop() ;
17             if (node == null)
18                 continue ;
19             res.add(node.val) ;
20             stack.push(node.left) ;
21             stack.push(node.right) ;
22         }
23         Collections.reverse(res) ;
24         return res ;
25     }
26 }

 

posted @ 2019-03-28 16:39  __Meng  阅读(105)  评论(0编辑  收藏  举报