zoukankan      html  css  js  c++  java
  • Leetcode543.Diameter of Binary Tree二叉树的直径

    给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

    示例 :

    给定二叉树

               1

               /

             2    3

            /

          4  5

    返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

    注意:两结点之间的路径长度是以它们之间边的数目表示。

    class Solution {
    public:
        int res = 0;
        int diameterOfBinaryTree(TreeNode* root) {
            if(root == NULL)
                return 0;
            res = max(res, GetDepth(root ->left) + GetDepth(root ->right) + 1);
            diameterOfBinaryTree(root ->left);
            diameterOfBinaryTree(root ->right);
            return res - 1;
        }
    
        int GetDepth(TreeNode* root)
        {
            if(root == NULL)
                return 0;
            return 1 + max(GetDepth(root ->left), GetDepth(root ->right));
        }
    };

  • 相关阅读:
    跟layout_weight说88,轻松搞定百分比布局
    跟闪退、程序崩溃说88
    程序的需求层次
    开博
    第十章 数组与集合 发牌程序 实例代码
    C#面向对象基础01
    winform form
    html
    C#语言基础02
    C#语言基础01
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10434066.html
Copyright © 2011-2022 走看看