我的算法6
来源:互联网 发布:综合评价算法 编辑:程序博客网 时间:2024/04/29 07:06
题目地址:https://leetcode.com/problems/diameter-of-binary-tree/#/description
题目描述: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.
* 我的代码* :
/** * 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 high_of_binary_tree(TreeNode* root){ if(root==NULL) return 0; int a=high_of_binary_tree(root->left); int b=high_of_binary_tree(root->right); int c=a>b?a:b; return c+1; } int diameterOfBinaryTree(TreeNode* root) { if(root==NULL) return 0; int a=high_of_binary_tree(root->left); int b=high_of_binary_tree(root->right); int c=diameterOfBinaryTree(root->left); int d=diameterOfBinaryTree(root->right); if(d>c) c=d; if(a+b>c) c=a+b; return c; }};
解题思路:
将最长路的可能出现情况分为三种,第一种是经过顶点,第二种是全部在左子树中,第三种是全部在右子树中。对于第一种,其长度显然为左子树高度加右子树高度,而第二、三种,可以递归得到。
最后,取三者中最大值即可。复杂度为O(n^2)。
0 0
- 我的算法6
- 直方图我的算法
- 我的排序算法
- 我的恋爱算法
- 我的算法
- 我的算法7
- 我的算法8
- 我的算法9
- 我的算法14
- 我的算法15
- 我的算法16
- 我的恋爱算法
- 我的算法模板
- 我的算法头文件
- 我写的KMP 算法
- 我的算法学习经历
- 我的五子棋人工智能算法
- 我的九宫格算法
- C语言之对队列、结构体、指针、数组的理解
- C++单元测试学习总结9
- FZU 1076 穿越沙漠(逆推建模)(数学)
- 微信小程序tips
- java对于复数的一些基本计算
- 我的算法6
- bzoj 3295: [Cqoi2011]动态逆序对 (CDQ分治+树状数组)
- es获取客户端方式
- 在使用selectSingleNode报NoClassDefFoundError
- Mysql数据库之主从分离
- Linux 内核时钟架构之时钟事件设备和tick_device绑定
- Linux下的粘滞位
- The builder launch configuration could not be found.项目启动报错
- oralce计算时间差