0
点赞
收藏
分享

微信扫一扫

性能优化利器:PyTorch中torch.cuda.Event的高效计时应用

1.965. 单值二叉树 - 力扣(LeetCode)

深度优先搜索,看边两端的结点是不是一样的值

class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        if(!root) return true;
        
        if(root->right) {
            if(root->val != root->right->val || isUnivalTree(root->right)) 
                return false;
        }

        if(root->left) {
            if(root->val != root->left->val || isUnivalTree(root->left))
                return false;
        }
        
        return true;
    }
};
2.543. 二叉树的直径 - 力扣(LeetCode)

class Solution {
public:
    int ans = 0;
    int dfs(TreeNode *t) {
        if(!t) return 0;
        int l = dfs(t->left);
        int r = dfs(t->right);
        ans = max( l+r, ans);
        // 精华之处
        return max(l, r) + 1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        dfs(root);
        return ans;
    }
};

把左边能走的最大长度找出来,把右边能走的最大长度找出来,答案是二者之和。

return max(l, r) + 1; 返回告诉父节点,基于当前这个结点的的最长路径是向左侧走还是右侧走

3.572. 另一棵树的子树 - 力扣(LeetCode)

class Solution {
public:
    bool check(TreeNode *o, TreeNode *t) {
        if(!o && !t)
            return true;

        if(!o && t || o && !t || o->val != t->val)
            return false;
        
        return check(o->left, t->left) && check(o->right, t->right);
    }
    
    bool dfs(TreeNode *o, TreeNode *t) {
        if(!o) 
            return false;
        
        return check(o, t) || dfs(o->left, t) || dfs(o->right, t);
    }

    bool isSubtree(TreeNode* root, TreeNode* subRoot) {
        return dfs(root, subRoot);
    }
};

 哎,其实懂也懂,但是自己想不出来。。。。。。。。。。。

我被自己蠢无语了。。。

举报

相关推荐

0 条评论