zoukankan      html  css  js  c++  java
  • 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);
        }
    }
  • 相关阅读:
    Ubuntu上VNC 配置
    Ubuntu远程桌面xrdp方法
    sudo 免密码
    Ubuntu 12.04 root默认密码? 如何使用root登录?
    DNS 和 IPv6 配置攻略
    计算机专业学习浅谈
    [图像]张正友论文翻译(2)
    [图像]张正友论文翻译(1)
    [图像]用Matlab在图像上画矩形框
    word如何修改尾注
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10191046.html
Copyright © 2011-2022 走看看