题解 | #在二叉树中找到两个节点的最近公共祖先# go

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

http://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116

go

/**
 * 
 * @param root TreeNode类 
 * @param o1 int整型 
 * @param o2 int整型 
 * @return int整型
*/
func lowestCommonAncestor( root *TreeNode ,  o1 int ,  o2 int ) int {
    // write code here
    if root == nil {
        return -1
    }

    var isParent func(root *TreeNode ,  o1 int ,  o2 int) *TreeNode
    isParent = func(root *TreeNode, o1, o2 int) *TreeNode {
        if root == nil {// 遇到null,返回null 没有LCA
            return root
        }
        // 遇到o1或o2,直接返回当前节点
        if root.Val == o1 || root.Val == o2 {
            return root
        }

         // 非null 非o1 非o2,则递归左右子树
        left := isParent(root.Left, o1, o2)
        right := isParent(root.Right, o1, o2)

        // 根据递归的结果,决定谁是LCA
        if left == nil {
            return right
        }
        if right == nil {
            return left
        }

        return root
    }


    node := isParent(root, o1, o2)
    if node != nil {
        return node.Val
    }
    return -1
}
全部评论

相关推荐

真烦好烦真烦:牛友太有实力了
点赞 评论 收藏
分享
AAA专业长城贴瓷砖刘大爷:这样的简历我会直接丢进垃圾桶,花里胡哨的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务