题解 | #农场牛群族谱#

农场牛群族谱

https://www.nowcoder.com/practice/7d28855a76784927b956baebeda31dc8

知识点

解题思路

递归判断整个树的结点,如果当前节点值等于p或者q就返回当前节点,把左右子树放进递归中再继续判断。

如果left不为空,right为空就返回left;right不为空,left为空就返回right;都不为空返回root,root就是他们公共的父节点。

Java题解

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param p int整型 
     * @param q int整型 
     * @return int整型
     */
    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        // write code here
        return fun(root,p,q).val;
    }

    public TreeNode fun(TreeNode root,int p, int q){
        if(root == null){
            return null;
        }
        if(root.val == p || root.val == q){
            return root;
        }
        TreeNode left = fun(root.left,p,q);
        TreeNode right = fun(root.right,p,q);
        if(left != null && right == null) {
            return left;
        }
        if(right != null && left == null){
            return right;
        }
        if(right != null && left != null){
            return root;
        }
        return null;
    }
}

全部评论

相关推荐

03-25 16:22
南华大学 Java
不敢追175女神:你是打了上千个招呼吧?😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务