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
    时间才能证明一切,选好了就尽力去做吧!
  • 相关阅读:
    (spring-第15回【IoC基础篇】)容器事件
    javascript笔记2-引用类型
    php namespace use 命名空间
    mysql性能优化(二)
    mysql常用命令
    关于有效的性能调优的一些建议[转]
    apache htaccess
    php 换行 空格分割处理
    一些比较好的博文
    php & 引用
  • 原文地址:https://www.cnblogs.com/tingxilin/p/11141287.html
Copyright © 2011-2022 走看看