第十四周LeetCode
来源:互联网 发布:新媒体传播 网络传播 编辑:程序博客网 时间:2024/05/16 05:42
题目
Longest Univalue Path
难度 Easy
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5 / \ 4 5 / \ \ 1 1 5
Output:
2Example 2:
Input:
1 / \ 4 5 / \ \ 4 4 5
Output:
2Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
实现思路
利用递归思想实现。对于每一个结点,求它的左子树和右子树的最长路径,如果结点的左节点值与该结点值相同,那么该节点的最长路径为左子树最长路径长度加一;同理如果与右子树的值相同,那么该节点的最长路径为右子树最长路径加一,如果左右子树的值都与该节点值相同,则该节点的最长路径为左子树最长路径加右子树最长路径。求得所有节点的最长路径后,取最大值返回。注意最长路径用边数表示。
实现代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ int longestUnivaluePath(TreeNode* root) { queue<TreeNode*> q; if (root) q.push(root); int depth; int longest = 0; while (!q.empty()) { TreeNode* u = q.front(); q.pop(); depth = findLongest(u->left,u->val)+findLongest(u->right,u->val); if (longest<depth) longest=depth; if (u->left) q.push(u->left); if (u->right) q.push(u->right); } return longest; } int findLongest(TreeNode* root, int val) { if (!root || root->val != val) return 0; int left = findLongest(root->left, val); int right = findLongest(root->right, val); return max(left,right)+1; }
阅读全文
0 0
- leetcode-python 第十四周
- leetcode-第十四周
- 第十四周leetcode题
- 第十四周LeetCode
- 第十四周LeetCode
- 第十四周LeetCode
- 第十四周LeetCode
- LeetCode题解 第十四周
- 第十四周:[leetCode] 120. Triangle
- Leetcode 算法设计 第十四周
- Leetcode 算法设计 第十四周
- Leetcode 算法设计 第十四周
- Leetcode 算法习题 第十四周
- 第十四周LeetCode算法题两道
- Leetcode 算法习题 第十四周
- Leetcode 算法习题 第十四周
- Leetcode 算法习题 第十四周
- Leetcode 算法习题 第十四周
- springboot实现kaptcha验证码
- Java类静态属性、静态块、非静态属性、非静态块、构造函数在初始化时的执行顺序
- MyBatis在insert插入操作时返回主键ID
- laravel自定义分页
- map用法
- 第十四周LeetCode
- Android网络编程:基础理论汇总
- 总结eclipse中安装maven插件
- unity中的2D虚拟摇杆和3D虚拟摇杆
- wow中常用动画名称及说明
- 安装Python basemap包
- mysql6.0安装
- 三道典型C语言题(7)
- Java中的锁