zoukankan      html  css  js  c++  java
  • leetcode 543. 二叉树的直径

    题目描述:

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

    示例 :
    给定二叉树

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

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

    思路分析:

    这道题翻译一下就是二叉树每个结点左右子树高度和的最大值。

    代码:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int maxh=0;
    13     int height(TreeNode* root)
    14     {
    15         if(root == nullptr)
    16             return 0;
    17         int l = height(root->left);
    18         int r = height(root->right);
    19         maxh = max(maxh, l+r);
    20         return max(l, r)+1;
    21     }
    22     int diameterOfBinaryTree(TreeNode* root) {
    23         if(root == nullptr)
    24             return 0;
    25         height(root);
    26         return maxh;
    27     }
    28 };
  • 相关阅读:
    STM
    backend flow
    Trace Sys
    CDC spyglass
    clock gating and PLL
    fault coverage enhancement
    008-docker-安装-tomcat:8.5.38-jre8
    007-docker-安装-mysql:5.6
    006-docker-安装-nginx
    005-docker-镜像:run、search、pull、commit、打tag
  • 原文地址:https://www.cnblogs.com/LJ-LJ/p/11435752.html
Copyright © 2011-2022 走看看