【leetcode】最长同值路径

 

/*当前节点于上一个相对根节点比较*/
int recursion(struct TreeNode* node, struct TreeNode* root,int* max){
    if(!node) return 0;
    int left = recursion(node->left,node,max);
    int right = recursion(node->right,node,max);
    if (left+right > *max) *max = left+right;
    return (node->val == root->val)? (left>right)? left+1: right+1 :0;
}
int longestUnivaluePath(struct TreeNode* root){
    int max=0;
    recursion(root,root,&max);
    return max;
}

 

/*当前节点于与左右两子节点比较*/
int longestUnivaluePath(struct TreeNode* root){
    int globle=0;
    UnivaluePath(root,&globle);
    return globle;
}

int UnivaluePath(struct TreeNode* root,int* globle){
   if(root==NULL){
       return 0;
   } 
    int l=UnivaluePath(root->left,globle);
    int r=UnivaluePath(root->right,globle);
    int left=0;
    int right=0;
    if(root->left&&root->val==root->left->val){
         left=l+1;   
    }
    if(root->right&&root->val==root->right->val){
         right=r+1;   
    }
    *globle=(*globle<left+right)?(left+right):(*globle);
    return left>right?left:right;
}

 

posted @ 2020-09-22 12:33  温暖了寂寞  阅读(193)  评论(0编辑  收藏  举报