/**
 * 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 max = 0;
        dfs(root, max);
        return max;
    }

    int dfs(TreeNode* root, int & max) {
        int l = 0, r = 0;

        if (root->left && root->left->val == root->val)
            l = 1 + dfs(root->left, max);
        else if (root->left)
            dfs(root->left, max);

        if (root->right && root->right->val == root->val)
            r = 1 + dfs(root->right, max);
        else if (root->right)
            dfs(root->right, max);

        if (l+r > max)
            max = l+r;

        return (l > r) ? l : r;
    }
};

 

补充一个python的实现:

 1 class Solution:
 2     def __init__(self):
 3         self.path = 0
 4         
 5     def lastOrder(self,root):
 6         if root == None:
 7             return 0
 8         left = self.lastOrder(root.left)
 9         right = self.lastOrder(root.right)
10         leftpath,rightpath = 0,0
11         if root.left != None:
12             leftpath = left + 1 if root.val == root.left.val else 0
13         if root.right != None:
14             rightpath = right + 1 if root.val == root.right.val else 0
15         self.path = max(self.path,leftpath+rightpath)
16         return max(leftpath,rightpath)
17     
18     def longestUnivaluePath(self, root: TreeNode) -> int:
19         self.lastOrder(root)
20         return self.path

 

posted on 2018-10-01 17:40  Sempron2800+  阅读(103)  评论(0编辑  收藏  举报