Pergunta de entrevista da empresa Meta

Given a binary tree, write a function to find the length of the longest path in the tree.

Respostas da entrevista

Sigiloso

3 de jan. de 2011

As I understood the question, It is required to get the longest path in a binary tree not a the max depth of the tree, it is required to get longest path in the tree between two nodes, which can be solved recursively by getting the max depth in the left and max depth in the right, and return the max between maxDepthLeft + maxDepthRight and previousSolution

5

Sigiloso

27 de fev. de 2011

The stumbling block here is that for each node, there are *two* things that must be done and two values that must be returned - the node must first figure out what is the longest path it sees (which is simply the sum of the max depth on each side) and it must also report the max depth for it's sub-tree so that it's parent node can figure out what is the longest path *it* can see and if the longest path instead passes though *it* instead of being somewhere in it's left and right subtrees. So each invocation of the function must return a pair - the longest path in that subtree and the max depth of that subtree. In this way, the first call (for root) can get the longest path so far for the left and right subtrees and also the max depths for each side. Then, it can be decided if the longest path is through the root or is in its left subtree or in its right subtree.

5

Sigiloso

24 de abr. de 2011

Do a dfs from the root to find a vertex that is most distant from the root and call it x. Call a dfs from x to find the most distant vertex from x and return it.

1

Sigiloso

18 de jan. de 2013

I don't think we can just find height of left and right subtrees and add together + 2. It's possible that there is an even longer path that exists in the left subtree itself. For example, there could be no right subtree at all and only a left subtree which branches out in both the right and left directions. The path with its center at the left subtree would be longer than left+right.

1

Sigiloso

20 de mai. de 2012

i think we can compute the height of the left sub tree and the height of the right sub tree, then add them together

Sigiloso

14 de abr. de 2011

Define a BST.depth function, call it on the left and on the right subtree, then add the two depths + 2 for the (root.left, root.right) path length.

Sigiloso

19 de dez. de 2010

Depth of Tree ... Use Queue if you want to do iteratively, else use recursion and get the depth.

1