1 题目
如题
2 Java
2.1 方法一()
public class PinDuoDuo_02 {
public static void main(String[] args) {
}
// TODO 这方法不好啊老铁!别再用返回值了,用成员变量;本解法返回的是 a/b 到公共父节点的距离
static int d = 0;
public static int helper(TreeNode root, TreeNode a, TreeNode b){
if(root == null || d != 0){
return 0;
}
int l = helper(root.left, a, b);
int r = helper(root.right, a, b);
int m = -1;
if(root.val == a.val || root.val == b.val){
m = 0;
}
// 左中右,a、b都包含
if((l != -1 && r != -1) || (l != -1 && m != -1) || (m != -1 && r != -1)){
d = l + r + m + 1;
return -1;
}
// 左中右,a、b仅包含 1个
// 注意!!!如果左节点是 a/b,返回根节点 1,而不是 0
if(l != -1 || r != -1 || m != -1) return l + r + m + 2 + 1;
// 左中右,a、b都不包含
return -1;
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){val = x;}
}
2.2 方法二(推荐)
public class PinDuoDuo_02 {
public static void main(String[] args) {
}
static int d = -1, dA = -1, dB = -1;
public static int helper1(TreeNode root, TreeNode a, TreeNode b){
if(root == null || d != -1){
return 0;
}
int l = helper(root.left, a, b);
int r = helper(root.right, a, b);
if(dA != -1) dA++;
if(dB != -1) dB++;
int m = 0;
if(root.val == a.val || root.val == b.val){
m = 1;
if(root.val == a.val) dA = 0;
else dB = 0;
}
// a、b 都包含
if(l + m + r == 2){
d = dA + dB;
return 0;
}
// a、b 仅含一个
if(l + m + r == 1) return 1;
// a、b 都不含
return 0;
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){val = x;}
}