zoukankan      html  css  js  c++  java
  • 543. Diameter of Binary Tree【Easy】【二叉树的直径】

    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.

    Accepted
    111,412
    Submissions
    241,330
    【解析】:
    对于每一个点,left 和 right depth 之和,就等于这个点的最大直径。换一句话说,就是这个点,左边能延伸出去最大值 + 右边能延伸出去的最大值,加一起,就等于这个点的左边最远的点到右边最远的点的距离。 就是最大直径。

    关键点:用post order去返回每一个点的depth(在之前depth值上+1),null点就返回0(base case);

        需要两个function,因为getDepth function 返回的都是depth,不是diameter,所以需要diameterOfBinaryTree 来单独返回diameter;

        每一个点的最大直径等于左边的depth 加上 右边的depth,取所有点中最大的值。

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

  • 相关阅读:
    hdoj-1005-Number Sequences
    FOJ-1058-粗心的物理学家
    程序设计第三次作业附加 代码规范
    简单数论
    FOJ-1001-Duplicate Pair
    链表初尝试-链表的构建与输出-指针
    函数递归简单题-hdoj-2044 2018-一只小蜜蜂 母牛的故事
    电路与电子学-第一章直流电路分析方法小概括
    DFS回溯-函数递归-xiaoz triangles
    进制转换 hdoj-2031
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10434918.html
Copyright © 2011-2022 走看看