题目:https://oj.leetcode.com/problems/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?
源码:Java版本算法分析:双栈。时间复杂度O(n),空间复杂度O(n)
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<TreeNode>();
Stack<Integer> cntStack=new Stack<Integer>();
TreeNode node=root;
int label;
do {
while(node!=null) {
stack.push(node);
cntStack.push(0);
node=node.left;
}
if(!stack.isEmpty()) {
node=stack.pop();
label=cntStack.pop();
if(label==0) {
cntStack.push(1);
stack.push(node);
node=node.right;
}else {
result.add(node.val);
node=null; //import
}
}
}while(!stack.isEmpty());
return result;
}
}
代码解释:cntStack用来标志顶点是第一次还是第二次出栈。第一次出栈需要访问其由节点,第二次出栈直接访问它。