298. Binary Tree Longest Consecutive Sequence #300
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.


Resolves: #58
Algorithm:
The intuition is pretty simple. If a node has a consecutive sequence (hereinafter cs) with the left branch and another on the right, the length of the cs at this node would have been the maximum of these two cs. If there is no consecutiveness with either left or right, we can assume than the length of the cs incoming from that direction is 0. If both are 0, the length of cs at this node can remain 1.
We can think this backwards too. If a node's value is consecutive to its parent's, then it should return the length of its cs, otherwise 0. At the base case of null leaves, they should return a length of 0. For this, we send the parent's value to a DFS of both left and right branches, receive their values and add the maximum one to 1. If the length of cs here is longer than the global maximum, we update it. I think the traversal here can be described as "postorder".