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].
解题报告:
递归解法是普通的后续遍历,不用多说,非递归用了一个栈来存储结点,想了好久也没想出可以不用栈或者链表的解法,思路如下:
如果想要输出一个结点,那么该结点要么是叶子结点,要么它的左右儿子结点都输出过了(如果只有左树那么输出的上一个结点应该是左儿子),所以用两个结点来保存当前结点和上一个输出的结点。
递归解法:
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> temp = new ArrayList<Integer>();
if(root == null)
return temp;
temp.addAll(postorderTraversal(root.left));
temp.addAll(postorderTraversal(root.right));
temp.add(root.val);
return temp;
}
}
非递归解法:
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> temp = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode pre = root,cur;
if(root == null) return temp;
stack.push(root);
while(stack.size() != 0){
cur = stack.peek();
if(cur.left == null && cur.right == null || cur.right == null && cur.left == pre || cur.right == pre){
temp.add(cur.val);
pre = stack.pop();
}
else{
if(cur.right != null)
stack.push(cur.right);
if(cur.left != null)
stack.push(cur.left);
}
}
return temp;
}
}