题解 | #农场牛群族谱#
农场牛群族谱
https://www.nowcoder.com/practice/7d28855a76784927b956baebeda31dc8
知识点:递归 遍历
思路:最能想到的就是求出到叶子节点的路径,然后对比路径即可找到最近公共祖先
但其实可以在递归过程中直接判断,主要是对递归的理解,
这里其实左右子树代表的就是是否找到p和q,找到就是p和q,找不到就是-1,和求最大值没多大区别
编程语言: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
//终止条件,找到值,或者节点为null
if(root == null)
return -1;
if(root.val == p || root.val == q)
return root.val;
//拿到子树的返回值集合,交叉对比就行了
int left = lowestCommonAncestor(root.left,p,q);//只拿返回值,就是子树的所有值集合,如果累加,则是累加起来的值
int right = lowestCommonAncestor(root.right,p,q);
//三种情况,left和right相遇,只找到left,只找到right
if(left !=-1 && right == -1)
return left;
if(right !=-1 && left ==-1)
return right;
if(right ==-1 && left ==-1)
return -1;
else
return root.val;
}
}
