题解 | #农场牛群族谱#
题目考察的知识点 : 二叉树遍历
题目解答方法的文字分析:
递归的方式深度遍历二叉树
对特殊情况进行判断:首先判断当节点为空时返回-1
其次判断值是否与输入中的一个相同,是则直接返回
当某节点左右子树返回值都大于0时,说明该节点就是输入节点的最近父节点
最后返回大于0的值
本题解析所用的编程语言: 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) {
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);
if(left >= 0 && right >= 0){
return root.val;
}
return left == -1 ? right : left;
}
}