zoukankan      html  css  js  c++  java
  • [LeetCode] Balanced Binary Tree

    Given a binary tree, determine if it is height-balanced.

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    这里要注意的是每个节点都要判断是否平衡,所以需要深搜下去。

    int depth(TreeNode *node) {
        if (!node) return 0;
        if (!node->left) {
            return 1 + depth(node->right);
        }
        else if (!node->right) {
            return 1 + depth(node->left);
        }
        return 1+max(depth(node->left), depth(node->right));
    }
    
    bool isBalanced(TreeNode *root) {
        if (!root) return true;
        int val = depth(root->left) - depth(root->right);
        if (abs(val) <= 1) {
            return isBalanced(root->left) && isBalanced(root->right);
        }
        return false;
    }
  • 相关阅读:
    ctrl+shift+k取消
    ERROR 1872
    swap
    mysql主从跳过错误
    undo
    gtid
    falcon监控指标
    连接数
    datetime与timestamp相互转换
    截取文件内容
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4059283.html
Copyright © 2011-2022 走看看