Recursion

Longest Increasing Stretch Downward

Given the root node of a binary tree root, return the length of the longest increasing stretch, strictly going downwards in the tree.

Example 1:

=> returns 3\notag \large \texttt{=> returns 3}

Explanation: The longest increasing stretch is "2,3,4", which has 3 nodes in it. The "1" is not a part of the longest stretch, since a stretch must go downwards.

Example 2:

=> returns 2\notag \large \texttt{=> returns 2}

Explanation: The longest increasing stretch is "1,2", which has 2 nodes in it.

First Few Test Cases:

0. Problem

We can solve this problem by visiting every node with a tree traversal. We'll grow each stretch as much as possible, and keep track of the biggest stretch we see.

We have to pass down the length of the parent stretch as an input parentLength. This is because it's impossible to know the size of a stretch, without passing it down from the parents. We also have to pass down the value of the parent node parentVal, so we know whether we should continue growing the stretch.

Here's the traversal that we'll write:

1. Recursion

The recursion is just a standard tree traversal. We need to pass down the correct inputs, so that the parentLength and parentVal are truly the length and value of the parent node. Here's the recursion:

To solve the problem, we should keep track of the biggest stretch length that we see, like this:

2. Base case

When we get to a null node, we should do nothing.

3. Code

To code this up, we combine the recursion and the base case. When can call the function to find the maximum length maxLen, and we return it as our answer.

Time Complexity O(n)O(n). We're walking through every node in the tree, and there are nn nodes.

Space Complexity O(n)O(n). We're using recursion, so we have to store calls in the Call Stack.

Mark as Completed:
Submits:
longestIncrStretch
Imports:
TreeNode
Test your code to get an output here!
longestIncrStretch(
)
Test your code to get an output here!