-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBTPostOrderTraversal.java
40 lines (36 loc) · 1.01 KB
/
BTPostOrderTraversal.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
39
40
/*
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
*/
import java.util.ArrayList;
import java.util.List;
public class BTPostOrderTraversal {
public static void main(String[] args) {
TreeNode root =new TreeNode(1);
root.left=null;
root.right=new TreeNode(2);
root.right.left=new TreeNode(3);
List<Integer> ans=postorderTraversal(root);
System.out.println(ans);
}
public static List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<>();
if(root==null){
return result;
}
result.addAll(postorderTraversal(root.left));
result.addAll(postorderTraversal(root.right));
result.add(root.data);
return result;
}
}
class TreeNode{
int data;
TreeNode left,right;
public TreeNode(int key){
key=data;
left=right=null;
}
}