目录
1.递归实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
print(list,root);
return list;
}
public static void print(List<Integer> list,TreeNode root){
if(root == null){
return;
}
print(list,root.left);
print(list,root.right);
list.add(root.val);
}
}
2.非递归实现(借助栈)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null){
return list;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
TreeNode pre = null;
while(!stack.isEmpty()){
TreeNode cur = stack.peek();
//前一条件是指拿出栈顶元素,若栈顶元素的左右孩子都为空,就直接将该结点入到list集合中
//后一条件是指栈顶元素的左右孩子都已经入到list集合中了,此时需要将cur结点入到list集合中
if((cur.left==null&&cur.right==null)||(pre!=null&&(cur.left==pre||cur.right==pre))){
list.add(cur.val);
pre = cur;
cur = stack.pop();
}else{
//注意先将右孩子入栈(后序遍历)
if(cur.right!=null){
stack.push(cur.right);
}
if(cur.left!=null){
stack.push(cur.left);
}
}
}
return list;
}
}