The answer is incorrect - another user correctly pointed out a bug. My solution below works only when the max length path passes through the root. In case, for example, the max length path is entirely in the left subtree and does not pass through the root, this answer fails. Feel free to read further to acquaint yourself with a recursive solution... and the bug in it.
I'm assuming that it is not important that the path has to have a difference of +1 as shown in your example. A difference of -1, resulting in a path like 4 -> 5 -> 4 -> 3 -> 4 -> 5 is ok as well.
public int getLongestConsecutivePath(TreeNode root) {
return root == null
? 0
: getLength(root.left, root.value) + getLength(root.right, root.value);
}
private int getLength(TreeNode node, int prevVal) {
return node == null || Math.abs(node.value - prevVal) > 1
? 0
: Math.max(getLength(node.left, node.value), getLength(node.right, node.value)) + 1;
}
Explanation:
- If the root is not null, we get the max length in left and right subtree and sum it.
- To get max length in a subtree, we recursively get the max length of right and left subtree of the subtree.
- If we have reached the leaf OR if we have reached a node where the difference in value is greater than 1, we return 0.
- Else we recursively get the max length from the left and right subtree and add 1 to it to accommodate for this node itself.
Math.Abs(node.value - parent.value) > 1. If that is true, there is no point in traveling down that path. - displayName