Leecode no.235 二叉搜索树的最近公共祖先

package tree;

/**
* 235. 二叉搜索树的最近公共祖先
* 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
*
* 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
*
* @author :Tang
* @date 2021/7/19
*/
public class LowestCommonAncestor {

int small = 0;
int big = 0;

/**
* 因为是二叉搜索树
* 通过判断当前节点的大小来判断是不是公共祖先
* 当前节点大于p && 小于q 说明当前节点是公共祖先
* 如果当前节点小于p 则递归当前节点的右子节点
* 如果当前节点大于q 则递归当前节点的左子节点
* (这里默认认为节点p的值大于节点q的值)
*
* @param root
* @param p
* @param q
* @return
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
big = Math.max(p.val, q.val);
small = Math.min(p.val, q.val);
return preSearch(root);
}

private TreeNode preSearch(TreeNode node){
if(node == null){
return null;
}
if(node.val < small){
return preSearch(node.right);
}

if(node.val > big){
return preSearch(node.left);
}
return node;
}

public static void main(String[] args) {

TreeNode node1 = new TreeNode(6);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(8);
TreeNode node4 = new TreeNode(0);
TreeNode node5 = new TreeNode(4);
TreeNode node6 = new TreeNode(7);
TreeNode node7 = new TreeNode(9);
TreeNode node8 = new TreeNode(3);
TreeNode node9 = new TreeNode(5);

node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
node3.left = node6;
node3.right = node7;
node5.left = node8;
node5.right = node9;
System.out.println(new LowestCommonAncestor().lowestCommonAncestor(node1, node2, node5).val);

}
}
posted @ 2021-07-19 16:11  六小扛把子  阅读(32)  评论(0编辑  收藏  举报