NC102 在二叉树中找到两个节点的最近公共祖先(Golang)

package main
import . "nc_tools"
/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
 * 
 * @param root TreeNode类 
 * @param o1 int整型 
 * @param o2 int整型 
 * @return int整型
*/
func lowestCommonAncestor( root *TreeNode ,  o1 int ,  o2 int ) int {
    // write code here
    return isParent(root,o1,o2).Val
}

func isParent(root *TreeNode,o1 int , o2 int) *TreeNode{
	//如果o1,o2 任何一个是现有树根节点,那么直接返回这个值
    if (root == nil ||root.Val == o1 || root.Val == o2){
        return root 
    }
    
    left := isParent(root.Left,o1,o2)
    right := isParent(root.Right,o1,o2)
    
    //一旦o1,o2都没有出现在左子树,随即到右子树去查询
    if left == nil{
        return right
    }
    //同上
    if right == nil {
        return left
    }
    //当以上条件判断结束 只会出现o1,o2都出现在以下面这个root为根节点的子树中,那么即该节点是最近的祖先节点(非最近的一定有左子树或者右子树查询不到o1或者o2)
    return root
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值