给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [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(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer>ans = new LinkedList<>();
post(root,ans);
return ans;
}
public void post(TreeNode root, List<Integer>ans){
if(root == null)
return;
if(root.left != null){
post(root.left,ans);
}
if(root.right != null){
post(root.right,ans);
}
ans.add(root.val);
}
}
迭代:
/**
* 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) {
LinkedList<Integer> ans = new LinkedList<>();
LinkedList<TreeNode> stack = new LinkedList<>();
if(root == null)
return ans;
stack.add(root);
while (!stack.isEmpty()){
TreeNode node = stack.pollLast();
ans.addFirst(node.val);
if(node.left != null){
stack.add(node.left);
}
if(node.right != null){
stack.add(node.right);
}
}
return ans;
}
}