-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBinaryTreeLongestConsecutiveSequence.java
112 lines (96 loc) · 3.17 KB
/
BinaryTreeLongestConsecutiveSequence.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// version 1: Traverse + Divide Conquer
public class Solution {
/**
* @param root the root of binary tree
* @return the length of the longest consecutive sequence path
*/
public int longestConsecutive(TreeNode root) {
return helper(root, null, 0);
}
private int helper(TreeNode root, TreeNode parent, int lengthWithoutRoot) {
if (root == null) {
return 0;
}
int length = (parent != null && parent.val + 1 == root.val)
? lengthWithoutRoot + 1
: 1;
int left = helper(root.left, root, length);
int right = helper(root.right, root, length);
return Math.max(length, Math.max(left, right));
}
}
// version 2: Another Traverse + Divide Conquer
public class Solution {
private int longest;
/**
* @param root the root of binary tree
* @return the length of the longest consecutive sequence path
*/
public int longestConsecutive(TreeNode root) {
longest = 0;
helper(root);
return longest;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
int subtreeLongest = 1; // at least we have root
if (root.left != null && root.val + 1 == root.left.val) {
subtreeLongest = Math.max(subtreeLongest, left + 1);
}
if (root.right != null && root.val + 1 == root.right.val) {
subtreeLongest = Math.max(subtreeLongest, right + 1);
}
if (subtreeLongest > longest) {
longest = subtreeLongest;
}
return subtreeLongest;
}
}
// version 3: Divide Conquer
public class Solution {
private class ResultType {
int maxInSubtree;
int maxFromRoot;
public ResultType(int maxInSubtree, int maxFromRoot) {
this.maxInSubtree = maxInSubtree;
this.maxFromRoot = maxFromRoot;
}
}
/**
* @param root the root of binary tree
* @return the length of the longest consecutive sequence path
*/
public int longestConsecutive(TreeNode root) {
return helper(root).maxInSubtree;
}
private ResultType helper(TreeNode root) {
if (root == null) {
return new ResultType(0, 0);
}
ResultType left = helper(root.left);
ResultType right = helper(root.right);
// 1 is the root itself.
ResultType result = new ResultType(0, 1);
if (root.left != null && root.val + 1 == root.left.val) {
result.maxFromRoot = Math.max(
result.maxFromRoot,
left.maxFromRoot + 1
);
}
if (root.right != null && root.val + 1 == root.right.val) {
result.maxFromRoot = Math.max(
result.maxFromRoot,
right.maxFromRoot + 1
);
}
result.maxInSubtree = Math.max(
result.maxFromRoot,
Math.max(left.maxInSubtree, right.maxInSubtree)
);
return result;
}
}