二叉树中俩节点的最短距离(pdd正式批2面)

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;}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值