Problem:
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.
Solution:
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
if (root == NULL)
return 0;
return max(longestUnivaluePath(root->left) + 1, longestUnivaluePath(root->right) + 1);
}
};
本文介绍了一个二叉树问题的解决方案:寻找最长路径,该路径上的所有节点都具有相同的值。此路径可以不经过根节点。文章提供了一段C++代码实现,通过递归方式计算从根节点开始左右子树中相同值节点的最长路径。
401

被折叠的 条评论
为什么被折叠?



