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?
先说二叉树递归的解法:
直接上代码:
public class MyOwnSolution {
public ArrayList<Integer> postorderTraversal(TreeNode root){
ArrayList<Integer> result = new ArrayList<Integer>();
if(root == null )
return result;
result.addAll(postorderTraversal(root.left));
result.addAll(postorderTraversal(root.right));
result.add(val);
return result;
}
}
addAll方法自己查api
下面写非递归方法:
首先把根节点push进栈里边
然后执行一个while循环,结束的条件是栈空:下边进行循环:
取出栈顶节点
if(栈顶节点为叶子节点):那么返回节点的值到数组里边,同时把栈顶节点压出栈;结束本次循环(continue)
if(栈顶节点左孩子不为空):那么把栈顶节点的左孩子压进栈,同时把左孩子标记为空(top.leftNode = null);结束本次循环(continue)
if(栈顶节点右孩子不为空):那么把栈顶节点的右孩子压进栈,同时把右孩子标记为空(top.leftNode = null);结束本次循环(continue)
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root){
Stack<TreeNode> stack = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
if(root == null){
return result;
}
stack.push(root);
while(!stack.isEmpty()){
TreeNode top = stack.peek();
if(top.left == null && top.right == null){
result.add(top.val);
stack.pop();
continue;
}
if(top.left != null){
stack.push(top.left);
top.left = null;
continue;
}
if(top.right != null){
stack.push(top.right);
top.right = null;
continue;
}
}
return result;
}
}
自己画一个二叉树,然后对着我的语言伪代码看一遍,肯定能懂
AC的一刻还是比较爽的!!!我想这就是坚持下去的原因