题目
分析
解决该题的思想还是递归地先处理子树问题
流程
递归返回左右子树的最长path
代码
c++版
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
if(root==nullptr) return 0;
int ans = 0;
univaluePath(root, ans);
return ans;
}
private:
int univaluePath(TreeNode* root, int& ans){
if(root==NULL) return 0;
int l = univaluePath(root->left, ans);
int r = univaluePath(root->right, ans);
int pl = 0;
int 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);
}
};
python版
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def __init__(self):
self.ans = 0
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def univaluePath(root):
if not root:
return 0
l = univaluePath(root.left)
r = univaluePath(root.right)
pl = 0
pr = 0
if root.left and root.val == root.left.val:
pl = l + 1
if root.right and root.val == root.right.val:
pr = r + 1
self.ans = max(self.ans, pl+pr)
return max(pl, pr)
if not root:
return 0
univaluePath(root)
return self.ans