LeetCode 687. Longest Univalue Path
Solution1:
参考链接:http://zxi.mytechroad.com/blog/tree/leetcode-687-longest-univalue-path/

/**
* 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) {
if (!root) return 0;
int ans = 0;
my_DFS(root, ans);
return ans;
}
int my_DFS(TreeNode* root, int& ans) {
int sum = 0;
if (!root) return 0;
int l = my_DFS(root->left, ans);
int r = my_DFS(root->right, ans);
int pl = 0, pr = 0;
if (root->left && root->val == root->left->val)
pl = l + 1;
if (root->right && root->val == root->right->val)
pr = r + 1;
ans = max(ans, pl + pr);
return max(pl, pr);
}
};
本文介绍了解决LeetCode 687题——最长相同路径的一种方法。通过深度优先搜索(DFS)策略,该算法遍历二叉树并记录最长的相同值路径。代码实现中详细展示了如何递归地计算每个节点的最长路径。
388

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



