543-二叉树的直径

543-二叉树的直径

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

示例 :
给定二叉树

      1
     / \
    2   3
   / \     
  4   5    

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    int maxdepth = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        if(root == null) {
            return 0;
        }

        scan(root);
        return maxdepth;
    }

    private int scan(TreeNode root) {
        if(root.right == null && root.left == null) {
            return 0;
        }

        int ld = 0;
        int rd = 0;
        if(root.right != null) {
            rd++;
            rd += scan(root.right);
        }
        if(root.left != null){
            ld++;
            ld += scan(root.left);
        }
        int depth = Math.max(ld, rd);
        maxdepth = Math.max(maxdepth, ld + rd);
        return depth;
    }

代码整理一下,得:

    int maxdepth = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        if(root == null) {
            return 0;
        }

        scan(root);
        return maxdepth;
    }

    private int scan(TreeNode root) {
        if(root.right == null && root.left == null) {
            return 0;
        }

        int ld = root.left != null ? 1 + scan(root.left) : 0;
        int rd = root.right != null ? 1 + scan(root.right) : 0;
        maxdepth = Math.max(maxdepth, ld + rd);
        return Math.max(ld, rd);
    }

猜你喜欢

转载自www.cnblogs.com/angelica-duhurica/p/12236992.html
今日推荐