• 543. Diameter of Binary Tree


    Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

    Example:
    Given a binary tree 

              1
             / 
            2   3
           /      
          4   5    
    

    Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

    Note: The length of path between two nodes is represented by the number of edges between them.

    time: O(n^2)  -- worst case, space: O(n)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int diameterOfBinaryTree(TreeNode root) {
            if(root == null) {
                return 0;
            }
            int d = depth(root.left) + depth(root.right);
            int left = diameterOfBinaryTree(root.left);
            int right = diameterOfBinaryTree(root.right);
            
            return Math.max(d, Math.max(left, right));
        }
        
        public int depth(TreeNode node) {
            if(node == null) {
                return 0;
            }
            return 1 + Math.max(depth(node.left), depth(node.right));
        }
    }

    optimized:

    time: O(n)  -- post order traverse, visited each node once,

    space: O(height)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        int max = 1;
        
        public int diameterOfBinaryTree(TreeNode root) {
            maxDiamter(root);
            return max - 1;
        }
        
        public int maxDiamter(TreeNode node) {
            if (node == null) {
                return 0;
            }
            int left = maxDiamter(node.left);
            int right = maxDiamter(node.right);
    
            max = Math.max(max, left + right + 1);
            return 1 + Math.max(left, right);
        }
    }
  • 相关阅读:
    优化Http请求、规则1减少Http请求 更新中
    js 验证日期格式
    SQL 在OPENQUERY中使用参数
    onpropertychange 和 onchange
    js 去掉空格
    检索 COM 类工厂中 CLSID 为 {000209FF00000000C000000000000046} 的组件时失败解决方法
    C#连接oracle数据库操作
    SQL游标
    MS SQL 设置大小写区别
    vs jquery 智能提示
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10191046.html
Copyright © 2020-2023  润新知