首页 > 其他 > 详细

Leetcode_687. 最长同值路径

时间:2020-05-10 00:16:15      阅读:59      评论:0      收藏:0      [点我收藏+]

求二叉树最长的同值路径。

dfs返回每个节点的左节点或右节点向上的最大距离,然后全局更新答案是左节点+右节点(如果左节点和右节点和根节点的值相同)。

code

/**
 * 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 ans=0;
    int dfs(TreeNode* root){
        if(root==NULL){
            return 0;
        }
        int le=dfs(root->left);
        int ri=dfs(root->right);
        if(root->left && root->val==root->left->val){
            le++;
        }else{
            le=0;
        }
        if(root->right && root->val==root->right->val){
            ri++;
        }else{
            ri=0;
        }
        ans=max(ans,le+ri);
        return max(le,ri);
    }
    int longestUnivaluePath(TreeNode* root) {
        dfs(root);
        return ans;
    }
};

Leetcode_687. 最长同值路径

原文:https://www.cnblogs.com/zxcoder/p/12861043.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!