Binary Tree Longest Consecutive Sequence: Post-Order Traversal
Problem is here: https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/
Best option is to perform a post-order tree traversal:
298. Binary Tree Longest Consecutive Sequence
Medium
Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
Example 1:
Input: 1 \ 3 / \ 2 4 \ 5 Output:3
Explanation: Longest consecutive sequence path is3-4-5
, so return3
.
Example 2:
Input: 2 \ 3 / 2 / 1 Output: 2 Explanation: Longest consecutive sequence path is2-3
, not3-2-1
, so return2
.
- Call for the left node
- Call for the right node
- Then calculate the value of the current node by checking whether the left AND the right are potential candidates for a sequence
Because the sequence has to be in increasing order, it limits the different conditions to check for. Still, there are some variations that need to be addressed, like when only one node exists, both exist, when only one node match the increasing condition, when both match, and so on. Code is down below, cheers, ACC.
public class Solution
{
public int LongestConsecutive(TreeNode root)
{
int longestEndingHere = 0;
int longest = 0;
LongestConsecutive(root, ref longestEndingHere, ref longest);
return longest;
}
private void LongestConsecutive(TreeNode node,
ref int longestEndingHere,
ref int longest)
{
if (node == null) return;
int leftLongestEndingHere = 0;
LongestConsecutive(node.left, ref leftLongestEndingHere, ref longest);
int rightLongestEndingHere = 0;
LongestConsecutive(node.right, ref rightLongestEndingHere, ref longest);
longestEndingHere = 1;
if (node.left == null && node.right == null)
{
//No-op
}
else if (node.left == null)
{
if (node.val + 1 == node.right.val)
{
longestEndingHere += rightLongestEndingHere;
}
}
else if (node.right == null)
{
if (node.val + 1 == node.left.val)
{
longestEndingHere += leftLongestEndingHere;
}
}
else
{
if (node.val + 1 == node.right.val && node.val + 1 == node.left.val)
{
longestEndingHere += Math.Max(leftLongestEndingHere, rightLongestEndingHere);
}
else if (node.val + 1 == node.right.val)
{
longestEndingHere += rightLongestEndingHere;
}
else if (node.val + 1 == node.left.val)
{
longestEndingHere += leftLongestEndingHere;
}
}
longest = Math.Max(longest, longestEndingHere);
}
}
Comments
Post a Comment