二叉树的后序遍历为先遍历左子树,再遍历右子树,最后获取根节点的值。
递归方式和先序,中序类似。
public class Solution {
public int[] postorderTraversal (TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root==null){
return new int[0];
}
dfs(list,root);
return list.stream().mapToInt(Integer::intValue).toArray();
}
public void dfs(List<Integer> list,TreeNode root){
if(root.left!=null){
dfs(list,root.left);
}
if(root.right!=null){
dfs(list,root.right);
}
list.add(root.val);
}
}
非递归方式
public int[] postorderTraversal (TreeNode root) {
if(root==null){
return new int[0];
}
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
TreeNode p = root;
s1.push(p);
while(!s1.empty()){
p=s1.pop();
s2.push(p);
if(p.left!=null){
s1.push(p.left);
}
if(p.right!=null){
s1.push(p.right);
}
}
int[] res = new int[s2.size()];
for(int i=0;i<res.length;i++){
res[i] = s2.pop().val;
}
return res;
}