Question:
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 nodes and are 2
8
6
. Another example is LCA of nodes 2
4
2
and are, since a node can be a descendant of itself according to the L CA definition.
Analysis:
Problem Description: Find the common ancestor of two nodes in a binary search tree (BST is characterized by the value of all nodes of the Zuozi is less than the value of the root node, and the value of all nodes of the right subtree is greater than the value of the root node).
1) Exclude special cases first;
2) If the value of the root node is greater than the maximum value of two nodes, then ancestor must be in the left subtree, recursive Zuozi;
3) If the value of the root node is less than the minimum value of two nodes, then ancestor must be in the right subtree, recursive right subtree;
4) Otherwise, the root node is equal to one of the values or greater than the left node is less than the right node, then ends recursively, returning the root node.
Answer:
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) {if(Root = =NULL|| p = =NULL|| Q = =NULL) return NULL; //if (p = = Root | | q = root)//If one is the root node, the root node must be the closest common ancestor//return root; if(Root.val < Math.min (P.val, Q.val))//Root is smaller than the smallest, which means that in the right sub-tree returnlowestcommonancestor (Root.right, p, q); Else if(Root.val > Math.max (p.val, Q.val))//Root is larger than the largest, indicating that in the left subtree returnlowestcommonancestor (Root.left, p, q); Else returnRoot; } }
2) Non-recursive method judgment (the efficiency is not very high AH. )
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) {if(Root = =NULL|| p = =NULL|| Q = =NULL) return NULL; TreeNode T=Root; while(true) { if(T.val > P.val && t.val >q.val) T=T.left; Else if(T.val < P.val && T.val <q.val) T=T.right; Else returnT; } } }
Leetcode--Lowest Common Ancestor of a Binary Search Tree