解题思路:采用递归的方式,先递归左子树,再递归右子树,然后保存根节点的值(左->右->根),时间复杂度O(n),空间复杂度O(n)
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
public int[] postorderTraversal (TreeNode root) {
// write code here
ArrayList<Integer> list = new ArrayList<>();
addToList(root, list);
return list.stream().mapToInt(x->x).toArray();
}
private void addToList(TreeNode root, ArrayList<Integer> list) {
if (root == null) {
return;
}
addToList(root.left, list);
addToList(root.right, list);
list.add(root.val);
}
}
扩展:采用非递归的方式实现
注意;先压左后压右,弹出的时候是先弹右后弹左,所以stack2保存的是根->右->左,最后将stack2弹出的时候就是左->右->根,这样就完成了二叉树的后序遍历
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
public int[] postorderTraversal (TreeNode root) {
// write code here
if (root == null) {
return new int[0];
}
ArrayList<Integer> list = new ArrayList<>();
Stack<TreeNode> stack1 = new Stack<>();
stack1.push(root);
//根->右->左
Stack<TreeNode> stack2 = new Stack<>();
while (!stack1.isEmpty()) {
TreeNode node = stack1.pop();
stack2.push(node);
//先压左后压右,弹出的时候是先弹右后弹左,所以stack2保存的是根->右->左,最后将stack2弹出的时候就是左->右->根
if (node.left != null) {
stack1.push(node.left);
}
if (node.right != null) {
stack1.push(node.right);
}
}
while (!stack2.isEmpty()) {
list.add(stack2.pop().val);
}
return list.stream().mapToInt(x->x).toArray();
}
}