Skip to content

Commit 9f6878f

Browse files
committedSep 30, 2018
Add solution 145
1 parent 93cf897 commit 9f6878f

File tree

3 files changed

+104
-0
lines changed

3 files changed

+104
-0
lines changed
 

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ Complete solutions to Leetcode problems, updated daily.
6060
| # | Title | Tags |
6161
|---|---|---|
6262
| 023 | [Merge k Sorted Lists](https://github.com/yanglbme/leetcode/tree/master/solution/023.Merge%20k%20Sorted%20Lists) | `Linked List`, `Divide and Conquer`, `Heap` |
63+
| 145 | [Binary Tree Postorder Traversal](https://github.com/yanglbme/leetcode/tree/master/solution/145.Binary%20Tree%20Postorder%20Traversal) | `Stack`, `Tree` |
6364

6465
## Contributions
6566
I'm looking for long-term contributors/partners to this repo! Send me PRs if you're interested! See the following:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
## 二叉树的后序遍历
2+
### 题目描述
3+
4+
给定一个二叉树,返回它的 后序 遍历。
5+
6+
示例:
7+
```
8+
输入: [1,null,2,3]
9+
1
10+
\
11+
2
12+
/
13+
3
14+
15+
输出: [3,2,1]
16+
```
17+
18+
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
19+
20+
### 解法
21+
22+
- 递归算法
23+
24+
先递归左子树,再递归右子树,最后访问根结点。
25+
26+
```java
27+
/**
28+
* Definition for a binary tree node.
29+
* public class TreeNode {
30+
* int val;
31+
* TreeNode left;
32+
* TreeNode right;
33+
* TreeNode(int x) { val = x; }
34+
* }
35+
*/
36+
class Solution {
37+
public List<Integer> postorderTraversal(TreeNode root) {
38+
List<Integer> list = new ArrayList<>();
39+
postorderTraversal(root, list);
40+
return list;
41+
}
42+
43+
private void postorderTraversal(TreeNode root, List<Integer> list) {
44+
if (root == null) {
45+
return;
46+
}
47+
postorderTraversal(root.left, list);
48+
postorderTraversal(root.right, list);
49+
list.add(root.val);
50+
}
51+
}
52+
```
53+
54+
- 非递归算法
55+
56+
57+
```java
58+
59+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// 递归版本
2+
/*
3+
class Solution {
4+
public List<Integer> preorderTraversal(TreeNode root) {
5+
List<Integer> list = new ArrayList<>();
6+
preorderTraversal(root, list);
7+
return list;
8+
}
9+
10+
private void preorderTraversal(TreeNode root, List<Integer> list) {
11+
if (root == null) {
12+
return;
13+
}
14+
list.add(root.val);
15+
preorderTraversal(root.left, list);
16+
preorderTraversal(root.right, list);
17+
}
18+
}
19+
20+
*/
21+
22+
// 非递归版本
23+
class Solution {
24+
public List<Integer> preorderTraversal(TreeNode root) {
25+
List<Integer> list = new ArrayList<>();
26+
Stack<TreeNode> stack = new Stack<>();
27+
while (root != null) {
28+
list.add(root.val);
29+
if (root.right != null) {
30+
stack.push(root.right);
31+
}
32+
if (root.left != null) {
33+
stack.push(root.left);
34+
}
35+
if (!stack.isEmpty()) {
36+
root = stack.pop();
37+
} else {
38+
break;
39+
}
40+
}
41+
42+
return list;
43+
}
44+
}

0 commit comments

Comments
 (0)
Please sign in to comment.