543. Diameter of Binary Tree

来源:互联网 发布:快典网藏头诗软件 编辑:程序博客网 时间:2024/06/06 01:34

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.

这道题和上一道题是差不多的,都是递归,先是每一步算出每个左右子树的深度,然后再每一步中都要计算最终的值,不断更新最终的值。
代码如下:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int maxx=0;    int diameterOfBinaryTree(TreeNode* root) {        depth(root);        return maxx;    }    int depth(TreeNode* root)    {        if(root==NULL)return 0;        int left=depth(root->left);        int right=depth(root->right);        maxx=max(maxx,left+right);        return max(left,right)+1;    }};
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 备孕三个月了还是没怀上怎么办 月子里喂奶腰疼怎么办 生完孩子子宫疼怎么办 记账凭证写错了怎么办 饥荒精神值为0怎么办 抓不住温暖我能怎么办 父亲打母亲我该怎么办 父亲对母亲家暴怎么办 摊上家暴的父亲怎么办 家暴警察不处理怎么办 父亲把母亲打了怎么办 u盘的文件打不开怎么办 头撞墙起包了怎么办 儿童头撞墙起包怎么办 头撞墙了鼓包了怎么办 北京65岁老年证怎么办 怎么办65岁免费乘车卡 5个月小孩晚上哭怎么办 婴儿要含奶头睡怎么办 我把输入法删了怎么办 头发干枯毛躁怎么办用什么洗发水 落枕后脖子歪了怎么办 睡觉睡得脖子疼怎么办? 婴儿脖子睡歪了怎么办 怀孕8个月肚皮痒怎么办 怀孕大阴唇肿了怎么办 孕妇肚皮撑的疼怎么办 我大阴唇特别长怎么办 切完洋葱辣眼睛怎么办 下昆山车没刷卡怎么办 高德地图用不了怎么办 玩游戏老是闪退怎么办 苹果平板电脑闪退怎么办 钉钉忘记打卡了怎么办 钉钉手机号换了怎么办 玖富叮当贷逾期怎么办 玖富超能怎么办现金贷 包包的油边开裂怎么办 lv包包油边开裂怎么办 lv钱包油边开裂怎么办 德运奶粉没勺子怎么办