Topic
Given A binary search tree (BST), find the lowest common ancestor (LCA) of the Given nodes in the BST.
Ideas
The topic requires a binary sorting tree of two nodes of the common parent node, said the popular point, in fact, the two nodes where the branch is the beginning of the fork. Find out this fork point.
For binary sort tree, one of its features is that the left subtree node of a node is smaller than that node, and the nodes of the right child of a node are larger than that node.
Therefore, we can find the common parent node by looking for the middle node of the two nodes.
Again, if a node is larger than the given node, the node must be on the left subtree of the current node; Similarly, if the current node is less than the given two nodes at the same time, the desired node must be on the right subtree of the node.
It is important to note that in the process of seeking, you also need to consider if the node you are seeking is one of two nodes. Also, when you find the current node, don't forget to verify that the node is the root of the tree there are no two of the given nodes (because it is possible that the given node is not on the tree).
Code
PublicBoolean exist (TreeNode root, TreeNode pnode) { while(root!=NULL){if(Pnode.Val==root.Val)return true;Else{if(Pnode.Val>root.Val) root = Root.right;Else{root = Root.left; } } }return false; } PublicTreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) {TreeNode currentnode = root;if(root==NULL)return NULL; while(Currentnode!=p && currentnode!=q) {if(p.Val<currentnode.Val&& Q.Val<currentnode.Val) {CurrentNode = Currentnode.left; }Else if(p.Val>currentnode.Val&& Q.Val>currentnode.Val) {CurrentNode = Currentnode.right; }Else{if(Exist (CurrentNode, p) && exist (CurrentNode, q))returnCurrentNode;Else{return NULL; } } }if(Exist (CurrentNode, p) && exist (CurrentNode, q))returnCurrentNode;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