题目描述
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
Example 1:
1 | Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 |
Example 2:
1 | Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 |
在BST中找到两个点的共同ancestor。
由于是个BST,所以只需要根据节点值来判断,从头开始,最先出现在p和q之间的值的节点就是他们最开始的共同节点。如果说当前节点小于p和q,就检查当前节点的右子节点;反之检查当前节点的左子节点。
代码实现
1 | class Solution { |