Leetcode ($): Lowest Common Ancestor of a Binary Search Tree

Source: Internet
Author: User

Given A binary search tree (BST), find the lowest common ancestor (LCA) of the Given nodes in the BST.

According to the definition of the LCA in Wikipedia: "The lowest common ancestor is defined between," nodes V and W as the L Owest node in T, have both V and W as descendants (where we allow a node to be a descendant of itself). "

        _______6______       /                  ___2__          ___8__   /      \        /         0      _4       7       9         /           3   5

For example, the lowest common ancestor (LCA) of nodes2and8Is6. Another example is LCA of nodes2and4Is2, since a node can be a descendant of itself according to the LCA definition.

/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *l Eft * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public:treenode* lowestcommonancestor (treenode* root, treenode* p, treenode* q) {if (!root) r Eturn NULL; treenode* tmp = root;while (TMP) {if (tmp = = P | | tmp = = q) {//if equal, return the node if (tmp = = p) return P;elsereturn Q;} else if ((P->val > Tmp->val && q->val < tmp->val) | | (P->val < Tmp->val && q->val > Tmp->val)) {//If one is greater than the current node and one is less than the current node, returns the current node return TMP;} else if (P->val < tmp->val && Q->val < Tmp->val) {//If it is less than the current node, two nodes are in the left subtree tmp = Tmp->left;}  else if (P->val > Tmp->val && q->val > Tmp->val) {<span style= "font-family:arial, Helvetica, Sans-serif; " >//If the node is greater than the current one, then the two nodes are </span> in the right subtree; 
TMP = Tmp->right;}} return NULL;    }};




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode ($): 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.