235. Lowest Common Ancestor of a Binary Search Tree
Last updated
Last updated
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:
Example 2:
Note:
All of the nodes' values will be unique. p and q are different and both values will exist in the BST.
得到最小公共祖先,对于BST来说不是很难,毕竟BST是有自己的“顺序”的,如果当前节点的值在给定的两个节点之间,直接可以返回当前节点。因为小的那个肯定在左子树,大的肯定在右子树
这里最差情况下,时间复杂度是O(lgn),最坏情况就是在最底层的叶子节点才找到最小公共祖先。