JAVA怎么求共同祖先_如何使用Java实现二叉树的最低共同祖先?

在树分支中标记数字的存在背后的基本思想是对数字FOUND使用非空指针,对NOTFOUND使用空指针.

一旦找到数字(p或q),或者根为空,调用堆栈就会回退.后来人们清楚地表明没有搜索到的号码.

有四种可能的情况:

1.)两位父母一方.

root

/ \

Leftsubtree Rightsubtree

p/q q/p

在这种情况下,在下面的代码中,如果(left!= null&& right!= null)返回root,则满足此时将到来;

2.)其他的父母.

q/p p/q

/ OR \

Leftsubtree Rightsubtree

p/q q/p

在这种情况下,如果(root == null || root == p || root == q)返回root,则会满足;

3.)它们中的任何一个都不存在于树中.

这种情况不会被发现.如第2种情况所示,该函数立即返回,无需进一步遍历并在其下方的树中查找其对应项.

4.)树中没有它们.

第一行if(root == null … return;将为每个不存在的子节点执行.最终结果将为null返回,因为找不到任何数字.

逐行代码说明.

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

if(root == null || root == p || root == q) return root;

/* (root == null) This proves that root is not in the branch of tree of our interest. Returning null would means NOTFOUND.*/

/* (root == p || root == q) either p or q or both are found. Returning non-null root would means FOUND. */

/*Check for presence in leftsubtree */

TreeNode left = lowestCommonAncestor(root.left, p, q);

/*Check for presence in rightsubtree */

TreeNode right = lowestCommonAncestor(root.right, p, q);

/* root

/ \

leftsubtree Rightsubtree

p/q q/p

*/

if(left != null && right != null) return root; //both the numbers are found inside tree under root

// left or right subtree OR both don't have p or q. Return the overall find result under root.

return left != null ? left : right;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值