-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree-longest-consecutive-sequence.cpp
75 lines (68 loc) · 1.88 KB
/
binary-tree-longest-consecutive-sequence.cpp
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
/*
* Copyright (c) 2018 Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <cstddef>
using namespace std;
class Solution {
public:
// https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/
int longestConsecutive(TreeNode *root) {
//
// Analysis
// --------
// - first solution that comes to mind is DFS / preorder traversal
// - running time is O(logN) in the best case scenario and O(N) in the
// worst.
//
// Obsevations
// -----------
// - NOT A BINARY SEARCH TREE!!!
// - Consecutive only means increasing by an integral value of 1.
// - We need to know
// a) parent to know if there has been an increase, and
// b) grandparent to know if there has been a break
// - Cannot pass the length of the run back as there will be breaks
// in consecutiveness throughout the tree, so pass the length and
// longest values forward.
//
// Corner cases
// ------------
// - root node, parent will be null, len is 1
// - children of root, gparent will be null
int longest = 0;
helper(nullptr, nullptr, root, 0, longest);
return longest;
}
protected:
static void helper(const TreeNode *gparent, const TreeNode *parent,
const TreeNode *node, int len, int &longest) {
if (nullptr == node) {
return;
}
if (nullptr == parent) {
len = 1;
} else {
// check for increasing
if (node->val == parent->val + 1) {
if (nullptr == gparent) {
len = 2;
} else {
if (parent->val == gparent->val + 1) {
len++;
} else {
len = 2;
}
}
} else {
len = 1;
}
}
if (len > longest) {
longest = len;
}
helper(parent, node, node->left, len, longest);
helper(parent, node, node->right, len, longest);
}
};