• leetcode-0543 二叉树的直径


    题目地址https://leetcode-cn.com/problems/diameter-of-binary-tree/

    递归+BFS(暴力解法)

    我们可以考虑在每个节点时,都去计算该节点左子树和右子树的最大高度。这样会包含大量的重复计算在里面。时间复杂度O(n^2) 空间复杂度O(n)

    class Solution {
        public int diameterOfBinaryTree(TreeNode root) {
            int result = 0;
            Queue<TreeNode> queue = new LinkedList<>();
            if (root == null) return result;
    
            queue.offer(root);
            while(!queue.isEmpty()) {
                TreeNode node = queue.poll();
                int currMaxDepth = maxDepth(node.left) + maxDepth(node.right) + 1;
                if (currMaxDepth > result)
                    result = currMaxDepth;
                if (node.left != null)
                    queue.offer(node.left);
                if (node.right != null)
                    queue.offer(node.right);
            }
    
            return result - 1;
        }
        private int maxDepth(TreeNode node) {
            if (node == null)
                return 0;
            return Math.max(maxDepth(node.left), maxDepth(node.right)) + 1;
        }
    }
    

    2.递归+BFS(优化解法)

    其实之前的maxDepth方法,已经是访问了所有节点的左子树和右子树的最大高度,这里我们只需要用个全局变量来缓存这个最大值即可,时间复杂度O(n) 空间复杂度O(h) h为树的最大深度

    class Solution {
        private int max;
        public int diameterOfBinaryTree(TreeNode root) {
            max = 1;
            maxDepth(root);
            return max - 1;
        }
        private int maxDepth(TreeNode node) {
            if (node == null)
                return 0;
            int left = maxDepth(node.left);
            int right = maxDepth(node.right);
            max = Math.max(max, left + right + 1);
            return Math.max(left, right) + 1;
        }
    }
    

    更多LeetCode题解和数据结构方面的内容,可以关注我的github,求个star~ ▄█▔▉●

  • 相关阅读:
    Python父类调用子类
    Python中for else注意事项
    JS Number类型数字位数及IEEE754标准
    cocos打包到ios与android上音频推荐
    JS学习之预解析(执行上下文)
    JS学习之函数的作用域
    JS学习之函数二
    JS学习之函数
    如何在subline中高亮显示.vue文件
    JS之正则
  • 原文地址:https://www.cnblogs.com/guolizhi/p/12771618.html
Copyright © 2020-2023  润新知