Description
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
1.The length of path between two nodes is represented by the number of edges between them.
2.The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
Example 1
Input:
5
/ \
4 5
/ \ \
1 1 5
Output:
2
Example 2
Input:
1
/ \
4 5
/ \ \
4 4 5
Output:
2
Solution 1(C++)
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
if (!root) return 0;
int longestPath=0;
helper(root, longestPath);
return longestPath;
}
private:
int helper(TreeNode* root, int& m){
int l=root->left ? helper(root->left, m) : 0;
int r=root->right ? helper(root->right, m) : 0;
l=(root->left && root->left->val==root->val) ? l+1 : 0;
r=(root->right && root->right->val==root->val) ? r+1 : 0;
m=max(m,l+r);
return max(l,r);
}
};
算法分析
这道题我认为可以看成是最长连续序列与树的结合。利用动态规划的方法可以解决。观察每一个节点。每一个节点所在可能路径最长相同连续序列的长度其实与其左子节点与右子节点有关,考虑到连续序列的特性,一旦不连续了,即根节点的值与左子节点或者与右子节点的值不相等了,那么左边的或者右边的就为0,如果相等,那么左边的或者右边的就各自加1。
这里要注意,关于长度的定义,两个节点长度为1,那么可以认为长度初始值为0,那么每新加一个节点,长度加1。
还是有些地方说不太清楚,给这个题目打了个心,以后在做一做。
程序分析
略。