forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestValues.java
More file actions
62 lines (54 loc) · 1.62 KB
/
LargestValues.java
File metadata and controls
62 lines (54 loc) · 1.62 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
package serach;
import java.util.ArrayList;
import java.util.List;
public class LargestValues {
public List<Integer> largestValues(TreeNode root){
List<Integer> res = new ArrayList<Integer>();
helper(root,res,0);
return res;
}
private void helper(TreeNode root, List<Integer> res, int d) {
if (root == null){
return;
}
//expand list size
if(d == res.size()){
res.add(root.val);
}else{
//or set value
res.set(d,Math.max(res.get(d),root.val));
}
helper(root.left,res,d+1);
helper(root.right,res,d+1);
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
@Override
public String toString() {
return "TreeNode{" +
"val=" + val +
", left=" + left +
", right=" + right +
'}';
}
}
public static void main(String[] args) {
TreeNode left = new TreeNode(9);
TreeNode right = new TreeNode(20,new TreeNode(15),new TreeNode(7));
TreeNode root = new TreeNode(3,left,right);
System.out.println(root.toString());
LargestValues largestValues = new LargestValues();
List<Integer> r = largestValues.largestValues(root);
System.out.println(r.toString());
}
}