leetcode#235 Lowest Common Ancestor of a Binary Search Tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.