LeetCode 145. 二叉树的后序遍历
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [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> ans = new ArrayList<Integer>();
dfs(root,ans);
return ans;
}
public void dfs(TreeNode root,List<Integer>ans){
if(root == null)
return;
dfs(root.left,ans);
dfs(root.right,ans);
ans.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> ans = new ArrayList<Integer>();
if(root == null)
return ans;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode pre = null;
while(root != null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
if(root.right == null || root.right == pre){
ans.add(root.val);
pre = root;
root = null;
}
else{
stack.push(root);
root = root.right;
}
}
return ans;
}
}
题目链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
题解参考:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/solution/er-cha-shu-de-hou-xu-bian-li-by-leetcode-solution/