zoukankan      html  css  js  c++  java
  • 110. 平衡二叉树

    给定一个二叉树,判断它是否是高度平衡的二叉树。

    本题中,一棵高度平衡二叉树定义为:

    一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

    示例 1:


    输入:root = [3,9,20,null,null,15,7]
    输出:true
    示例 2:


    输入:root = [1,2,2,3,3,null,null,4,4]
    输出:false
    示例 3:

    输入:root = []
    输出:true
     

    提示:

    树中的节点数在范围 [0, 5000] 内
    -104 <= Node.val <= 104

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        bool isBalanced(TreeNode* root) {
            if(root == nullptr) return true;
            return (abs(treeHeight(root->left) - treeHeight(root->right)) <= 1) && 
                    isBalanced(root->left) && isBalanced(root->right);
        }
    
        int treeHeight(TreeNode* root) {
            if(root == nullptr) return 0;
            return max(treeHeight(root->left), treeHeight(root->right)) + 1;
        }
    };
  • 相关阅读:
    inline-block 文字与图片不对齐
    js去除数组重复项
    react2
    kfaka windows安装
    sigar 监控服务器硬件信息
    Disruptor
    Servlet 3特性:异步Servlet
    jvmtop 监控
    eclipse如何debug调试jdk源码
    一致性hash算法
  • 原文地址:https://www.cnblogs.com/mjn1/p/14281675.html
Copyright © 2011-2022 走看看