zoukankan      html  css  js  c++  java
  • leetcode每日刷题计划-简单篇day17

    嘻嘻嘻提前做了算到新的一天,吃烤肉巨开心呀

    Num 110 平衡二叉树

    注意是每一层都要平衡才行,刚开始只记得判断root了

    /**
     * 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:
        bool isBalanced(TreeNode* root) {
            if(root==NULL) return true;
            if(abs(getLevel(root->left)-getLevel(root->right))>1) 
               return false;
            return (isBalanced(root->left) && isBalanced(root->right));
        }
        int getLevel(TreeNode*root)
        {
            if(root==NULL) return 0;
            return max(getLevel(root->left),getLevel(root->right))+1;
        }
    };
    View Code

     Num 111 二叉树的最小深度

    题不难但是仍然没有一次做对,这个求得是最短深度,注意一下,如果左边有点右边没有,这时候不能当成右边是0。比如[1,2]是两层的,在解决树相关的问题的时候注意一下。

    第一,要注意是不仅仅判断root,第二,要考虑到对叶子节点和null节点

    /**
     * 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 minDepth(TreeNode* root) {
            if(root==NULL) return 0;
            if(root->left==NULL && root->right==NULL) return 1;
            if(root->left==NULL) return minDepth(root->right)+1;
            if(root->right==NULL) return minDepth(root->left)+1;
            return min(minDepth(root->left),minDepth(root->right))+1;
        }
    };
    View Code
    时间才能证明一切,选好了就尽力去做吧!
  • 相关阅读:
    【leetcode】538/1038: 把二叉搜索树转化为累加树
    k8s-nginx二进制报Illegal instruction (core dumped)
    k8s-记一次安全软件导致镜像加载失败
    Ubuntu1804下k8s-CoreDNS占CPU高问题排查
    Ubuntu 18.04 永久修改DNS的方法
    NLP资源
    《转载》14种文本分类中的常用算法
    PyCharm 使用技巧
    python模块包调用问题
    强化学习(8)------动态规划(通俗解释)
  • 原文地址:https://www.cnblogs.com/tingxilin/p/11141287.html
Copyright © 2011-2022 走看看