Problem Definition:
Given A binary search tree (BST), find the lowest common ancestor (LCA) of the Given nodes in the BST.
According to the definition of LCA in Wikipedia: "The lowest common ancestor is defined between
Nodes V and W as the lowest node in T have both V and W as descendants (where we allow a node to be a descendant O F itself). "
Idea: Start with the root node:
1) If the value of the root node equals one of the nodes, the root node is the lowest common ancestor to be found, returning it;
2) sort to ensure p<=q;
3) If the root node value is greater than p and less than Q, then p and Q are respectively in the root node of the left and right subtree, the root node is the lowest common ancestor to find, return it;
4) If the root node value is greater than the large q, then p and Q are all in the left subtree of the root node, leaving the root node the left child node as the new root node, and if the root node value is less than the smaller p, then p and Q are all in the right subtree of the root node
The right child node of the other root node is the new root node;
5) recursively (1)-->4).
Code:
#Definition for a binary tree node.#class TreeNode:#def __init__ (self, x):#self.val = x#self.left = None#self.right = NoneclassSolution:#@param {TreeNode} root #@param {TreeNode} p #@param {TreeNode} q #@return {TreeNode} defLowestcommonancestor (self, root, p, q):if(Root.val==p.val)or(root.val==q.val):returnRootifP.val>Q.val:p,q=q,pifP.val<root.val androot.val<Q.val:returnRootifRoot.val>Q.val:root=Root.leftifroot.val<P.val:root=Root.rightifroot!=None:returnself.lowestcommonancestor (Root, p, q)
leetcode#235 Lowest Common Ancestor of a Binary Search Tree