Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created October 19, 2018 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/e00bdf7e6b43c8e89dd2df6b0759f4a2 to your computer and use it in GitHub Desktop.
Save jianminchen/e00bdf7e6b43c8e89dd2df6b0759f4a2 to your computer and use it in GitHub Desktop.
I gave the hints to help the interviewee to learn the algorithm
Leetcode: longest univalue path
hint:
instead of working on longest path directly, kind of greedy, break into two parts.
length1 = one is the root to leaf node longest path -> left side
length2 = one is the root to leaf node longest path -> right side
path cross the root = length1 + length2
In order to calculate length1 or length2, recursive can be used to calculate. Brute force all paths
from the tree, any node to any node, n nodes in the tree, n * (n-1) = O(n*n). It is hard to compute.
Instead brute force every node as root node of the tree, determine the longest path cross the root node.
More hint:
work on those simple trees:
4 4 4 4
/ / \ / \
4 4 4 4 4
/
4
Recursive function:
return 0, 1, 1, 2
longest path:
return 0, 1, 2, 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment