给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> keys = new ArrayList<>();
postorderTraversal(root, keys);
return keys;
}
public static void postorderTraversal(TreeNode root, List<Integer> keys){
if(root == null){
return;
}
//先遍历左子树
postorderTraversal(root.left, keys);
//再遍历右子树
postorderTraversal(root.right, keys);
//遍历根节点
keys.add(root.val);
}
}
迭代:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
//后序遍历:left->right->root 倒过来是root->right->left 则此过程和前序遍历相似
//前序遍历迭代是:root->left->right
while(!stack.isEmpty()){
TreeNode node = stack.pop();
if(node == null){
continue;
}
list.add(node.val);
if(node.left!=null){
stack.push(node.left);
}
if(node.right!=null){
stack.push(node.right);
}
}
Collections.reverse(list);
//正确的结果需要对list进行翻转
return list;
}
}