Farthest Distance From a Node in a Binary Tree
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) → intExamples
Example 1
root = [1,2,3,4,5,null,6]target = 2return = 3The farthest node is 6, reached along 2 - 1 - 3 - 6.
Example 2
root = [7]target = 7return = 0The target is the only node.
Example 3
root = [1,2,null,3,null,4]target = 3return = 2Both node 1 and node 4 are two edges from the target.
Constraints
- The tree contains from
1through200000nodes. - Every node value is a signed 32-bit integer.
- All node values are unique.
targetoccurs in the tree.