forked from qiurunze123/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lc145.java
38 lines (37 loc) · 1 KB
/
lc145.java
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
package code;
/*
* 145. Binary Tree Postorder Traversal
* 题意:二叉树后序遍历
* 难度:Hard
* 分类:Stack, Tree
* 思路:调整的先序遍历,再反转结果
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
public class lc145 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList();
if(root==null)
return res;
Stack<TreeNode> st = new Stack();
while(!st.isEmpty()||root!=null){
while(root!=null) {
st.add(root);
res.add(root.val);
root = root.right; //先遍历右节点
}
root = st.pop();
root =root.left; //再左节点
}
Collections.reverse(res); //反转链表
return res;
}
}