Farthest Distance From a Node in a Binary Tree
Updated
Problem statement
You are given the root of a binary tree and the unique value target of one node in that tree.
You may move along each parent-child edge in either direction. Find the longest path from the target node to any node without repeating a node. Return the number of edges on that path.
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 = 2From target 3, node 1 is two edges away along 3 - 2 - 1, while node 4 is one edge away. The maximum distance is 2.
Constraints
- The tree contains from
1through200000nodes. - Every node value is a signed 32-bit integer.
- All node values are unique.
targetoccurs in the tree.
More Google Phone Screen questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Periodic-Color Binary Forest RootsPHONE SCREEN · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Best Stock Trade with Buy and Sell DaysPHONE SCREEN · Seen Nov 2026
- Word Chain Jumps in a GridPHONE SCREEN · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
- Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
- Course Schedule Cycle DetectionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Distance Between Two Tree NodesAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Tree DiameterQualcomm · PHONE SCREENQualcomm interview questions
- Frog Position After T SecondsInMobi · PHONE SCREENInMobi interview questions
- Hubs With the Shortest Longest ChainAdobe · PHONE SCREENAdobe interview questions
- Tree Pythagorean TriplesIBM · OAIBM interview questions
- Diameter of an Acyclic Undirected GraphSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Binary Tree Nodes at Distance KApple · ONSITE INTERVIEWApple interview questions
- Find the Tree DiameterAdyen · ONSITE INTERVIEWAdyen interview questions
- Binary Tree Nodes at Distance KGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Maximum Data Transfer TimeMicrosoft · OAMicrosoft interview questions