[LeetCode]543. Diameter of Binary Tree
来源:互联网 发布:ie6修复软件 编辑:程序博客网 时间:2024/06/06 20:48
[LeetCode]543. Diameter of Binary Tree
题目描述
思路
最长路径必然是先从下往上,再从上往下,因此使用DFS,同时来维护一个最大值,在DFS的过程中,返回的是当前节点到左子节点对应的叶节点和右子节点对应的叶节点的最大距离,同时返回后与当前的maxLength比较,若左右子节点的和更大,则更新。
代码
#include <iostream>#include <algorithm>using namespace std;struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public: int maxLength = 0; int nodeDepth(TreeNode* node) { if (!node) return 0; int lLength = nodeDepth(node->left); int rLength = nodeDepth(node->right); maxLength = max(maxLength, lLength + rLength); return max(lLength + 1, rLength + 1); } int diameterOfBinaryTree(TreeNode* root) { nodeDepth(root); return maxLength; }};int main() { TreeNode* r1 = new TreeNode(1); TreeNode* r2 = new TreeNode(1); TreeNode* r3 = new TreeNode(1); TreeNode* r4 = new TreeNode(1); TreeNode* r5 = new TreeNode(1); r1->left = r2; r1->right = r3; r2->left = r4; r2->right = r5; Solution s; cout << s.diameterOfBinaryTree(r1) << endl; system("pause");}
0 0
- Leetcode-543. Diameter of Binary Tree
- [leetcode] 543. Diameter of Binary Tree
- 【Leetcode】543. Diameter of Binary Tree
- [LeetCode]543. Diameter of Binary Tree
- [LeetCode]543. Diameter of Binary Tree
- leetcode-543. Diameter of Binary Tree
- [leetcode]-543. Diameter of Binary Tree
- LeetCode 543. Diameter of Binary Tree
- (LeetCode) 543. Diameter of Binary Tree
- leetcode 543. Diameter of Binary Tree
- LeetCode 543. Diameter of Binary Tree
- [leetcode]: 543. Diameter of Binary Tree
- [leetcode: Python]543. Diameter of Binary Tree
- leetcode 543. Diameter of Binary Tree
- Leetcode 543. Diameter of Binary Tree
- [LeetCode] 543. Diameter of Binary Tree
- LeetCode-543. Diameter of Binary Tree (Java)
- Leetcode-543. Diameter of Binary Tree
- Linux Centos6 安装Nginx详细图解教程
- KVC,字典转模型 & 泛型数组
- IAR MAP/ICF 文件学习
- HDFS报错
- Python-序列化和反序列化
- [LeetCode]543. Diameter of Binary Tree
- duboo资料集
- 二叉树
- Linux下对目录进行操作所需权限
- sentiment treebank
- iOS之Settings.Bundle
- java关于三元运算符
- Hive 元数据信息查询
- Qt中显示复杂列表