给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [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> result = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
if(root==null){
return result;
}
stack.add(root);
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
result.add(0,temp.val);
if(temp.left!=null){
stack.add(temp.left);
}
if(temp.right!=null){
stack.add(temp.right);
}
}
return result;
}
}
递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> result = new LinkedList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root==null){
return result;
}
helper(root);
return result;
}
public void helper(TreeNode root){
if(root==null){
return;
}
helper(root.left);
helper(root.right);
result.add(root.val);
}
}