-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path145. 树的后序遍历.java
More file actions
72 lines (61 loc) · 1.84 KB
/
Copy path145. 树的后序遍历.java
File metadata and controls
72 lines (61 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package 树的遍历;
// 145. 二叉树的后序遍历
/**
* 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> postoderList = new ArrayList<>();
// postorderTree(postoderList, root);
// return postoderList;
// }
// private void postorderTree(List<Integer> list, TreeNode root){
// if(root == null){
// return;
// }else{
// postorderTree(list, root.left);
// postorderTree(list, root.right);
// list.add(root.val);
// }
// }
// }
/**
* 后序,迭代
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> postoderList = new ArrayList<>();
if(root == null){
return postoderList;
}
Stack<TreeNode> treeStack = new Stack<>();
treeStack.push(root);
while(!treeStack.isEmpty()){
TreeNode tempNode = treeStack.pop();
postoderList.add(tempNode.val);
if(tempNode.left != null){
treeStack.push(tempNode.left);
}
if(tempNode.right != null){
treeStack.push(tempNode.right);
}
}
Collections.reverse(postoderList); // 迭代的push过程是先根,再left,再right,因此迭代的遍历过程为“根右左”,因此将其反转,变成了后序的“左右根”
return postoderList;
}
}