【问题标题】:Diameter of Binary Tree Off by 1二叉树直径减1
【发布时间】:2020-04-21 09:00:42
【问题描述】:

我是递归和树的新手。我无法计算出二叉树的直径。我的解决方案差 1,我不知道我哪里出错了。我在这里查看了一个类似的问题:Finding Diameter of a Tree 但我无法理解它是否确实是同一个问题。下图的答案直径为 8(两个节点之间的最长路径)。但是我得到了 7。任何帮助或建议表示赞赏。提前致谢。

问题可以在这里找到:https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3293/

在 106 个测试用例中,我只失败了 4 个。

public class DiameterBinaryTree {

    public static void main(String argv[]){
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        System.out.println(diameter(root));
    }

    public static int diameter(TreeNode root){
        int maxDiameter = Integer.MIN_VALUE;
        return diameterHelper(root, maxDiameter) ;
    }

    public static int diameterHelper(TreeNode root, int maxDiameter){
        if(root == null ) return 0;
        diameterHelper(root.left, maxDiameter);
        int leftHeight = findHeight(root.left);
        diameterHelper(root.right, maxDiameter);
        int rightHeight = findHeight(root.right);
        return Math.max(maxDiameter, leftHeight + rightHeight) ;
    }

    public static int findHeight(TreeNode root ){
        int countLeft = Integer.MIN_VALUE;
        int countRight = Integer.MIN_VALUE;
        return findHeightHelper(root, countLeft, countRight) ;
    }

    public static int findHeightHelper(TreeNode root, int countLeft, int countRight){
        if(root == null ) return 0;
        countLeft = 1 + findHeightHelper(root.left, countLeft, countRight);
        countRight = 1 + findHeightHelper(root.right, countLeft, countRight);
        return Math.max(countLeft, countRight) ;
    }
}

【问题讨论】:

    标签: java algorithm graph tree binary-tree


    【解决方案1】:

    在比较当前直径之前,我没有考虑他左侧的最大直径和右侧的最大直径。

    return Math.max(Math.max(leftDiameter, rightDiameter), leftHeight + rightHeight);

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多