給定一個二叉樹糕韧,返回它的 后序 遍歷芥备。
示例:
輸入: [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;
}
}