1,题目要求
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.
求一个二叉树的最长的路径,要求路径上所有节点的值都是相同的。
其中路径的长度为节点之间的边的条数,路径不要求从根节点开始。
2,题目思路
利用迭代的办法,创建一个辅助的函数。
3,程序源码
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
if(root == nullptr) return 0;
int maxLen = -1;
getLen(root, root->val, maxLen);
return maxLen;
}
private:
int getLen(TreeNode* node, int val, int& maxLen){
if(node == nullptr) return 0;
int left = getLen(node->left, node->val, maxLen);
int right = getLen(node->right, node->val, maxLen);
maxLen = max(maxLen, left + right);
if(node->val == val) return max(left, right) + 1;
else return 0;
}
};