code ganker说这个的非递归很难,看了半天觉得好麻烦,看到discussion里面有个特别天才的解法!!
preorder 是root-left-right, postorder是 left-right-root。那么稍微改一下preorder 变成 root-right-left 那个么就和postorder顺序完全相反了!!只要Collections.reverse就行!!
代码:
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while ( !stack.isEmpty() || root != null ){
if ( root != null ){
list.add(root.val);
stack.push(root);
root = root.right;
}
else{
root = stack.pop();
root = root.left;
}
}
Collections.reverse(list);
return list;
}
}
code ganker的解法是说记录当前节点和pre节点 以便于检查他们之间的父子关系,看现在是在向上走还是向下走,代码如下:
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
stack.push(root);
TreeNode pre = null;
while(!stack.isEmpty())
{
TreeNode cur = stack.peek();
if(pre==null || pre.left==cur || pre.right==cur)
{
if(cur.left!=null)
{
stack.push(cur.left);
}
else if(cur.right!=null)
{
stack.push(cur.right);
}
else
{
res.add(cur.val);
stack.pop();
}
}
else if(cur.left==pre && cur.right!=null)
{
stack.push(cur.right);
}
else
{
res.add(cur.val);
stack.pop();
}
pre = cur;
}
return res;
}