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