• 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.

    思路:其实所谓的二叉树的“直径”其实就是节点左右子树的最大深度和,而现在需要求出这个和的最大值。在递归求二叉树的深度时,记录下当前每个节点的深度,比较出最大值即可。

     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 diameterOfBinaryTree(TreeNode* root) 
    13     {
    14       res = 1;
    15       treeDepth(root);
    16       return res - 1;
    17     }
    18     int treeDepth(TreeNode* node)
    19     {
    20       if(node == nullptr)
    21         return 0;
    22       int L = treeDepth(node->left);
    23       int R = treeDepth(node->right);
    24       res = max(res,L+R+1);
    25       return max(L,R)+1;
    26     }
    27   private:
    28   int res;
    29 };
  • 相关阅读:
    k8s管理pod资源对象(上)
    k8spod资源的基础管理操作
    k8s名称空间资源
    bootstrap表格 之多选数据的获取
    sql server 查询表的创建时间
    C# Bootstrap table之 分页
    C# 基于Bootstrap的三级联动
    C# 后台构造json数据
    C# bootstrap之表格动态绑定值
    C# 文件的一些基本操作
  • 原文地址:https://www.cnblogs.com/Swetchine/p/11254594.html
Copyright © 2020-2023  润新知