Skip to content

Conversation

@ErdemT09
Copy link
Collaborator

@ErdemT09 ErdemT09 commented Jun 5, 2021

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".

@altay9
Copy link
Collaborator

altay9 commented Jun 5, 2021

I think the traversal here can be described as "postorder".

You are right.
In in-order traversal nodes are like apples falling down the tree.

In post-order traversal, it is like wrapping a tree in a veil or blanket that first touches the tree's outer nodes.

Therefore post-order looks appropriate to calculate that kind of distances.

image

Copy link
Collaborator

@altay9 altay9 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quite fine Erdem. Thanks.
image

@ErdemT09 ErdemT09 merged commit 3154043 into master Jun 6, 2021
@ErdemT09 ErdemT09 deleted the 298.-Binary-Tree-Longest-Consecutive-Sequence branch June 6, 2021 03:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

298. Binary Tree Longest Consecutive Sequence

3 participants