543. 二叉树的直径

深度优先搜索

class Solution {

    public int diameterOfBinaryTree(TreeNode root) {

        if (root == null){
            return 0;
        }

        /**
         * 包含根节点的最长路径
         */
        int containRoot = maxDepth(root.left) + maxDepth(root.right);

        /**
         * 左右子树的路径
         */
        int leftDepth = diameterOfBinaryTree(root.left);
        int rightDepth = diameterOfBinaryTree(root.right);

        int maxChild = Math.max(leftDepth, rightDepth);

        return Math.max(containRoot, maxChild);
    }

    public int maxDepth(TreeNode root){

        if (root == null){
            return 0;
        }

        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(logn)
 */

优化1——等效于求所有节点的最大深度

class Solution {

    int max = 0;

    public int diameterOfBinaryTree(TreeNode root) {

        depth(root);
        return max;
    }

    /**
     * 在《104. 二叉树的最大深度》的基础上
     * 顺便计算其中深度最大的节点的值
     */
    public int depth(TreeNode root){

        if (root == null){
            return 0;
        }

        int left = depth(root.left);
        int right = depth(root.right);
        max = Math.max(left + right, max);

        return Math.max(left, right) + 1;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(logn)
 */

https://leetcode-cn.com/problems/diameter-of-binary-tree/

posted @ 2021-12-28 20:42  振袖秋枫问红叶  阅读(29)  评论(0)    收藏  举报