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 and the nodes P and Q as the L Owest node in T, have both P and Q as descendants (where we allow a node to be a descendant of itself). "
Given binary Search tree:root = [6,2,8,0,4,7,9,null,null,3,5]
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
Example 1:
Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output:6
Explanation:the LCA of Nodes 2 and 8 is 6.
Example 2:
Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output:2
Explanation:the LCA of Nodes 2 and 4 is 2, since a node can a descendant of itself
According to the LCA definition.
Note:
* All of the nodes ' values would be unique.
* p and Q are different and both values would exist in the BST.
Take advantage of the BST feature.
1. If the root value is in the middle of the two numbers to be searched, two nodes are distributed in the left and right subtree, and the current root is the LCA.
2. If the root value and two numbers are equal, the node of the two numbers is a parent-child relationship, and the current root is the LCA.
Take the above two rules for the recursive exit, and then do the recursion.
Similar question: Lowest Common Ancestor of a Binar tree:https://www.cnblogs.com/jasminemzy/p/9698483.html
Realize:
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/classSolution { PublicTreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) {if(Root = =NULL|| Root.val = = P.val | | Root.val = =q.val) {returnRoot; } if(Root.val > P.val && root.val < Q.val | | Root.val < p.val && Root.val >q.val) {returnRoot; } TreeNode Left=lowestcommonancestor (Root.left, p, q); TreeNode Right=lowestcommonancestor (Root.right, p, q); returnLeft! =NULL?Left:right; }}
Leetcode235-lowest Common Ancestor of a Binary Search tree-easy