问题描述:
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.
示例:
Input:
5 / \ 4 5 / \ \ 1 1 5
Output:
2
Input:
1 / \ 4 5 / \ \ 4 4 5
Output:
2
Note: 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) {}
* };
*/
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
int res = 1;
queue<TreeNode *> que;
if (root == nullptr) return 0;
que.push(root);
while (!que.empty())
{
int size = que.size();
for (int i = 0; i < size; i++)
{
TreeNode * r = que.front();
que.pop();
if (r->left) que.push(r->left);
if (r->right) que.push(r->right);
int re = bl(r->left,r->val) + bl(r->right,r->val) + 1;
if (res < re) res = re;
}
}
return res - 1;
}
int bl(TreeNode* root,int val)
{
if (root == nullptr || root->val != val) return 0;
int left = bl(root->left, val);
int right = bl(root->right, val);
return max(left, right) + 1;
}
};