方法1: 这道题是postorder traversal,我还是第一次碰到。之前preorder和inorder已经做的基本很熟练了。这次的postorder还是有一些tricky的,需要一下小技巧,不过只要记住这个技巧就好了。第一种方法 dfs-postorder-recursion。时间复杂n,空间复杂h。
/**
* 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<>();
if(root == null) return list;
dfs(root, list);
return list;
}
public void dfs(TreeNode root, List<Integer> list){
if(root.left != null) dfs(root.left, list);
if(root.right != null) dfs(root.right, list);
list.add(root.val);
}
}
方法2: dfs-postorder-iteration。这个方法是有一点小聪明的,建议自己看一遍lc官方解答2的动画解释就全明白了。时间复杂n,空间复杂h。
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> output = new LinkedList();
Stack<TreeNode> stack = new Stack<>();
if (root == null) return output;
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
output.addFirst(root.val);
if (root.left != null) stack.push(root.left);
if (root.right != null) stack.push(root.right);
}
return output;
}
}
方法3: 正儿八经的dfs-postorder-iteration。建议看lc官方解答3的动画解释,也挺好理解的。时间复杂n,空间复杂h。
/**
* 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<>();
while(root != null || !stack.isEmpty()){
while(root != null){
if(root.right != null){
stack.push(root.right);
}
stack.push(root);
root = root.left;
}
root = stack.pop();
if(!stack.isEmpty() && root.right == stack.peek()){
stack.pop();
stack.push(root);
root = root.right;
}else{
list.add(root.val);
root = null;
}
}
return list;
}
}
总结:
- 94 inOrder
- 144 preOrder
- 145 postOrder