leetcode-504-Diameter of Binary Tree
来源:互联网 发布:java nexttoken 编辑:程序博客网 时间:2024/06/08 02:39
问题
题目:[leetcode-504]
思路
刚上来的时候做错了,因为觉得二叉树的直径一定要经过root。所以我求出了左右子树的深度,加起来获得答案。
思路是不对的,因为直接可能是不经过root的。这点很重要。
那么我的思路是,对于每一个节点,就出经过他的最大直径。
然后,二叉树的直接就是这些当中最大的。
代码
/** * 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 diameterOfBinaryTree(TreeNode* root) { if(!root) return 0; else{ int max = 0; dfs(root, max); return max; } }private: int depth(TreeNode* root){ if(!root) return 0; else return std::max( depth(root->left), depth(root->right) ) + 1; } int helper(TreeNode* root){//经过root的最大直径 if(!root) return 0; else return depth(root->left) + depth(root->right); } void dfs(TreeNode* root, int& ans){ if(!root) return; else{ int tmp = helper(root); ans = std::max(ans, tmp); dfs(root->left, ans); dfs(root->right, ans); } }};
0 0
- leetcode-504-Diameter of Binary Tree
- leetcode-504-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】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
- 二分查找
- android app性能优化大汇总(UI渲染性能优化)
- 对于php、mysql优化、angularjs的一些小感悟
- leetcode-504-Diameter of Binary Tree
- poj 2142 数论 扩展欧几里得
- leetcode-504-Diameter of Binary Tree
- C++后台开发 网络编程实践一
- boost库入门
- Servlet分页技术
- 三种简单排序算法
- JavaScript-正则表达式
- C++STL库之algorithm库
- javaScript之String字符串
- java菜鸟回炉之旅之二----认识java