FastPrepFarthest Distance From a Node in a Binary Tree

Farthest Distance From a Node in a Binary Tree

Google logoGoogle● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

You are given the root of a binary tree and the unique value target of one node in that tree.

Treat every parent-child edge as traversable in both directions. Return the maximum number of edges on a simple path from the target node to any node in the tree.

Function

farthestDistance(root: TreeNode, target: int) → int

Examples

Example 1

root = [1,2,3,4,5,null,6]target = 2return = 3

The farthest node is 6, reached along 2 - 1 - 3 - 6.

Example 2

root = [7]target = 7return = 0

The target is the only node.

Example 3

root = [1,2,null,3,null,4]target = 3return = 2

Both node 1 and node 4 are two edges from the target.

Constraints

  • The tree contains from 1 through 200000 nodes.
  • Every node value is a signed 32-bit integer.
  • All node values are unique.
  • target occurs in the tree.

More Google problems

See Google hiring insights
public int farthestDistance(TreeNode root, int target) {
    // write your code here
}
root[1,2,3,4,5,null,6]
target2
expected3
Checking account…