zoukankan      html  css  js  c++  java
  • Leetcode_687. 最长同值路径

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

    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;
        }
    };
    
  • 相关阅读:
    23-10 条件查询
    22-9 聚合函数
    关系抽取snowball
    关系抽取bootstrap
    NER
    GPT
    因果卷积 空洞卷积
    XL-NET
    transoformer-XL
    transoformer
  • 原文地址:https://www.cnblogs.com/zxcoder/p/12861043.html
Copyright © 2011-2022 走看看