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(n2), Space: O(h)
    //这道题乍一眼看上去需要两个递归函数,对于每一个点要自己调用自己diameterOfBinaryTree,对于某一个点要调用dfs计算深度,但其实再仔细想不需要第一个递归,因为dfs在递归的同时已经可以计算出来周长了
        int diameter  = 0;
        
        public int diameterOfBinaryTree(TreeNode root) {
            if (root == null) {
                return 0;
            }
    
            dfs(root);
            return diameter;
        }
        
        private int dfs(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int left = dfs(root.left);
            int right = dfs(root.right);
            diameter = Math.max(diameter,left + right);//这里不加1, 因为周长算得是线段而不是点,比如只有一个node为1的点,周长为0.
            return 1 + Math.max(left,right);
        }
  • 相关阅读:
    BUAA OO Unit1 表达式求导
    中介者模式
    命令模式
    观察者模式
    解释器模式
    策略模式
    迭代器模式
    模板方法模式
    代理模式
    桥接模式
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9774328.html
Copyright © 2011-2022 走看看