【leetcode】104,110,111总结

【111. Minimum Depth of Binary Tree】
这里写图片描述
「思路」
利用深度优先算法,预先设定一个比较大的ans值,不断更新ans的最小值,最终找到最短路径。
「代码」

class Solution {
public:
    int ans=100000000;
    int minDepth(TreeNode* root) {
        if(!root)return 0;
        DFS(root,1);
        return ans;
    }
    void DFS(TreeNode* root,int a)
    {
       if(!root) return;
       if(!root->left && !root->right)
       {
           ans=min(ans,a);
           return;
       }
        a++; 
        DFS(root->left,a);
        DFS(root->right,a);
    }
};

【104. Maximum Depth of Binary Tree】
这里写图片描述
「思路」
通过寻找最小路径的算法改编而成。同样利用深度优先算法,预先设定一个ans为0,不断更新ans的最大值,最终找到最长路径。
「代码」

class Solution {
public:
    int ans=0;
    int maxDepth(TreeNode* root) {
        if(!root)return 0;
        DFS(root,1);
        return ans;
    }
    void DFS(TreeNode* root,int a)
    {
       if(!root) return;
       if(!root->left && !root->right)
       {
           ans=max(ans,a);
           return;
       }
        a++; 
        DFS(root->left,a);
        DFS(root->right,a);
    }
};

【110. Balanced Binary Tree】

这里写图片描述
「思路」
借用上述的求最长路径的算法,计算出每条路径的长度。用isBalanced函数做判断,判断左右子树的长度差,如果差大于1则返回false。
「运行结果」
这里写图片描述
「代码」

class Solution {
public:
    int dif=0,ansmax=0;    
    bool isBalanced(TreeNode* root)
    {
        if(!root || (!root->left && !root->right)) return true;        
        DFS_max(root->left,0);
        int left=ansmax;
        ansmax=0;
        cout<<left<<"l"<<endl;
        DFS_max(root->right,0);
        int right=ansmax;
        ansmax=0;
        cout<<right<<"r"<<endl;
        if(abs(left-right)>1) return false;
        else if (!isBalanced(root->left) || !isBalanced(root->right)) return false;
        else return true;
    }

    void DFS_max(TreeNode* root,int a)
    {
       if(!root)
       {
           ansmax=max(ansmax,a);
           return;
       }
        a++; 
        DFS_max(root->left,a);
        DFS_max(root->right,a);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值