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);
        }
    }
  • 相关阅读:
    html表单
    html基础
    MySQL数据库 数据的更新
    JAVA数据库编程
    集合框架
    线程和进程
    反射
    centos 7环境
    js中的this
    javascript的作用域以及闭包现象
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10191046.html
Copyright © 2011-2022 走看看