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 0
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- 543. Diameter of Binary Tree
- Diameter of Binary Tree
- 欢迎使用CSDN-markdown编辑器
- 继承中无参构造的用法
- 性能测试
- python IDE(Integrated Develope Environment集成开发环境)
- centos : yacc&lex gcc cannot find -ll/-lfl
- 543. Diameter of Binary Tree
- 人工智能、机器学习和神经网络 你真的知道它是什么意思吗
- hdoj1058 Humble Numbers(值得注意的简单题)
- 【IO流】BufferedReader,BufferedWriter处理流(缓冲流)按行读取
- Linux学习之二十五(Linux文档压缩及归档,gz/bz2/xz/zip/Z)
- NYOJ
- Windows下swoole扩展的编译安装部署
- vue--过滤器
- A. UCloud 机房的网络搭建