1650. Lowest Common Ancestor of a Binary Tree III
递归
Last updated
Was this helpful?
递归
Last updated
Was this helpful?
Given two nodes of a binary tree p
and q
, return their lowest common ancestor (LCA).
Each node will have a reference to its parent node. The definition for Node
is below:
According to the : "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)."
Example 1:
Example 2:
Example 3:
Constraints:
The number of nodes in the tree is in the range [2, 10
5
]
.
-10
9
<= Node.val <= 10
9
All Node.val
are unique.
p != q
p
and q
exist in the tree.
对比 另一个LCA 提供ROOT 自顶向下, 这个只有俩子,自下而上。
总步数相同
第一次遍历:
pointer1
走 a
步到 LCA,再走 b
步到 q
的起始位置。
pointer2
走 b
步到 LCA,再走 a
步到 p
的起始位置。
第二次遍历:
此时,pointer1
和 pointer2
都走了 a + b
步,必定在 LCA 处相遇。
有点类似快慢指针的思想