← 返回 amazon 的题目列表Lowest Common Ancestor in Binary Tree
类型:online_judge
Find the Lowest Common Ancestor in a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two specified nodes. The LCA is defined as the lowest node in the tree that has both nodes as descendants.
Requirements
The tree contains at most 10^4 nodes.
Each node has a unique value.
It is not guaranteed the nodes are present in the tree, return the ancestor if it exists.
Input
Input is a root of a binary tree and two nodes for which the LCA needs to be found.
Output
Return the node representing the lowest common ancestor.
Example
Input:
[3,5,1,6,2,0,8,null,null,7,4]
Node 1: 5
Node 2: 1
Output: 3
Input:
[3,5,1,6,2,0,8,null,null,7,4]
Node 1: 5
Node 2: 4
Output: 5
Test cases
Input: Root=[3], Node 1=3, Node 2=3
Input: Root=[3, 5], Node 1=5, Node 2=3
Input: Root=[3, 5, 1, 6, 2], Node 1=6, Node 2=2
Input: Root=[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], Node 1=7, Node 2=4
Input: Root=[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], Node 1=10, Node 2=4
Example
Input
[3], 3, 3