https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
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 LCA Definition.
Problem Solving Ideas:
CC150 4.7, but the original question is any binary tree, here is more simple, is limited to a two-fork search tree.
Depending on the nature of BST, Root.left.val < Root.val < Root.right.val, and all subtrees are BST. Our train of thought becomes the judgment of where P and q are in root.
1. If both are less than root.val, must be at the same time on the left, Root is not LCA, recursively search the left subtree.
2. If both are greater than root.val, search for the right subtree recursively.
3. Otherwise, Root is the LCA on both sides of root.
/*** 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) { return NULL; } if(root = = P | | root = =q) {returnRoot; } TreeNode Left=lowestcommonancestor (Root.left, p, q); TreeNode Right=lowestcommonancestor (Root.right, p, q); if(left = =NULL|| right = =NULL) { returnleft = =NULL?Right:left; } returnRoot; }}
The time complexity of the algorithm above is O (Logn), which is equal to the height of the tree. The following algorithm can be used in any binary tree, not necessarily BST.
The root is the LCA of P and Q only when Root is found in both the left and right sub-trees, respectively, with P and Q. Otherwise, the returned null is not found, and the found side returns p or Q.
/*** 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) { return NULL; } if(root = = P | | root = =q) {returnRoot; } TreeNode Left=lowestcommonancestor (Root.left, p, q); TreeNode Right=lowestcommonancestor (Root.right, p, q); if(left = =NULL|| right = =NULL) { returnleft = =NULL?Right:left; } returnRoot; }}
The above solution has a time complexity of O (n).
Lowest Common Ancestor of a Binary Search Tree