LeetCode brush title: recent common ancestor binary search tree (day38)
Subject description:
Given a binary search tree, find the nearest common ancestor of the two specified nodes of the tree.
Baidu Encyclopedia recent common ancestor as defined: "For two nodes of the root of the tree T p, q, is represented as a common ancestor node x, that x is p, q ancestor depth as large as possible and x (a node can be its own ancestors). "
For example, given the following binary search tree: root = [6,2,8,0,4,7,9, null, null, 3,5]
Example 1:
Input: root = [6,2,8,0,4,7,9, null, null, 3,5], p = 2, q = 8
Output: 6
Explanation: nodes 2 and 8 is the common ancestor 6.
Example 2:
Input: root = [6,2,8,0,4,7,9, null, null, 3,5], p = 2, q = 4
Output: 2
Explanation: nodes 2 and 4 are common ancestor 2, because by definition a recent common ancestor node can be a node itself.
Description:
The value of all nodes are unique.
p, q, and for different nodes are present in a given binary search tree.
Idea: using the characteristics of binary search tree
On the code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//利用二叉搜索树的特性
TreeNode res = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
lca(root, p , q);
return res;
}
public void lca(TreeNode root, TreeNode p , TreeNode q){
if((root.val - p.val)*(root.val - q.val) <= 0){
res = root;
}else if(root.val < p.val && root.val < q.val){
lca(root.right, p , q);
}else{
lca(root.left, p , q);
}
}
}
Results of the:
Time-consuming: