Skip to content

Commit 2e9540f

Browse files
committed
add solution of problem 145: binary tree post order traversal
1 parent 0b7f8ff commit 2e9540f

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
Given a binary tree, return the *postorder* traversal of its nodes' values.
2+
3+
For example:
4+
Given binary tree `{1,#,2,3}`,
5+
```
6+
1
7+
\
8+
2
9+
/
10+
3
11+
```
12+
return `[3,2,1]`.
13+
14+
Note: Recursive solution is trivial, could you do it iteratively?
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
public class Solution {
11+
public List<Integer> postorderTraversal(TreeNode root) {
12+
List<Integer> result = new ArrayList<Integer>();
13+
14+
if (root != null)
15+
postorderTraversal(root, result);
16+
17+
return result;
18+
}
19+
20+
private void postorderTraversal(TreeNode node, List<Integer> result) {
21+
if (node.left != null)
22+
postorderTraversal(node.left, result);
23+
24+
if (node.right != null)
25+
postorderTraversal(node.right, result);
26+
27+
result.add(node.val);
28+
}
29+
}

0 commit comments

Comments
 (0)