知识点
树
解题思路
递归判断整个树的结点,如果当前节点值等于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;
}
}



京公网安备 11010502036488号