42.哀家要长脑子了!

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);
    }
};

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

我被自己蠢无语了。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值