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 everynode never differ by more than 1.

    这道题目总是理解错,最开始理解就是左子树的任何一个叶子节点和右子树的任何一个叶子节点的depth差不能大于1. 并且左右子树都是平衡的,所以设了leftMinDep, leftMaxDep,rightMinDep, rightMaxDep,然后minDep = min(leftMinDep, rightMinDep), maxDep = max(leftMaxDep, rightMaxDep), maxDep - minDep <= 1。

    但看到红字,可以看到depth of a tree是定义为一棵树的节点最大深度,所以应该判断abs(leftTreeDep - rightTreeDep) <= 1。

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool checkBalance(TreeNode *node, int &dep)
    13     {
    14         if (node == NULL)
    15         {
    16             dep = 0;
    17             return true;
    18         }
    19         
    20         int leftDep, rightDep;
    21         bool leftBalance = checkBalance(node->left, leftDep);
    22         bool rightBalance = checkBalance(node->right, rightDep);
    23         
    24         dep = max(leftDep, rightDep);
    25         
    26         return leftBalance && rightBalance && (abs(rightDep - leftDep) <= 1);
    27     }
    28     
    29     bool isBalanced(TreeNode *root) {
    30         // Start typing your C/C++ solution below
    31         // DO NOT write int main() function
    32         int dep;
    33         return checkBalance(root, dep);
    34     }
    35 };
  • 相关阅读:
    Nginx作为缓存服务
    Nginx作为代理服务
    ZipUtils zip压缩实现
    getman九桃小说解析油猴脚本
    maven添加代理加速jar包下载
    ffmpeg MP3 flv 视频转mp3
    ActiveMQ配置用户认证信息
    JS实现HTML标签转义及反转义
    删除registry镜像数据,以centos为例
    启动一个带登录账号密码的registry容器
  • 原文地址:https://www.cnblogs.com/chkkch/p/2742987.html
Copyright © 2011-2022 走看看