题解 | #农场牛群族谱# java
农场牛群族谱
https://www.nowcoder.com/practice/7d28855a76784927b956baebeda31dc8
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
if (root == null)
return -1;
if (root.val == p || root.val == q)
return root.val;
int l = lowestCommonAncestor(root.left, p, q);
int r = lowestCommonAncestor(root.right, p, q);
if (l >= 0 && r >= 0)
return root.val;
return l == -1 ? r : l;
}
}
所使用的语言是Java。
该题目考察的知识点是二叉树(Binary Tree)以及递归算法。题目要求找到二叉树中给定两个节点的最低共同祖先节点。
这段代码的文字解释如下:
- 定义了一个名为
lowestCommonAncestor的方法,该方法接收一个名为root的TreeNode类型参数,以及两个整型参数p和q,并返回一个整型结果。 - 在
lowestCommonAncestor方法中,首先检查root是否为null,如果是,则返回 -1。 - 然后检查当前节点的值是否等于
p或q,如果是,则当前节点即为所求的最低共同祖先节点,直接返回节点的值。 - 如果当前节点不是最低共同祖先节点,则从左右子树中递归调用
lowestCommonAncestor方法分别找到p和q的最低共同祖先节点。 - 如果左右子树的结果都不为 -1,则说明
p和q分别位于当前节点的左右子树中,当前节点即为最低共同祖先节点,返回当前节点的值。 - 如果左子树的结果为 -1,则说明
p和q都位于右子树中,返回右子树的结果。 - 如果右子树的结果为 -1,则说明
p和q都位于左子树中,返回左子树的结果。

