二叉树的最近公共祖先

 

 

 

https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/solution/236-er-cha-shu-de-zui-jin-gong-gong-zu-xian-hou-xu/

 

 

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */


//祖先节点根据q、p节点的相对位置,存在三种情况,根据这三种情况去递归子树找公共节点即可
//1、p 和 q 分别在root节点的左、右子树中;
//2、p = root ,且 q 在 root 的左或右子树中;
//3、q = root ,且 p 在 root 的左或右子树中;


func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
    if root==nil{
        return nil
    }
    if root.Val==p.Val||root.Val==q.Val{// 如果p,q为根节点,则公共祖先为根节点
        return root
    }
    if find(root.Left,p)&&find(root.Left,q){// 如果p在左子树,并且q也在左子树,则在左子树查找公共祖先
        return lowestCommonAncestor(root.Left,p,q)
    }
    if find(root.Right,p)&&find(root.Right,q){
        return lowestCommonAncestor(root.Right,q,p)//如果p在右子树,并且q也在右子树,则在右子树查找公共祖先
    }
    return root // 如果p,q分属两侧,则公共祖先为根节点
}

// 判断target节点是否在root子树里面
func find(root,target *TreeNode) bool{
    if root==nil{
        return false
    }
    if root.Val==target.Val{
        return true
    }
    return find(root.Left,target)||find(root.Right,target)
}

 

 

 二叉树的建立:https://www.cnblogs.com/-citywall123/p/16434923.html

 
posted @ 2022-07-01 15:56  知道了呀~  阅读(62)  评论(0编辑  收藏  举报