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 };
  • 相关阅读:
    【初学EXT】布局练习
    创建型模式总结(补充UML类图)
    数据库基本概念总结
    Word2010操作技巧总结
    VMWare虚拟机磁盘压缩和上网总结
    第一次用word2010发布文章到博客园记
    设计模式学习总结一原则及创建型模式
    为什么要开始写blog?
    Delphi异常处理总结
    设计模式总结之行为型模式
  • 原文地址:https://www.cnblogs.com/chkkch/p/2742987.html
Copyright © 2011-2022 走看看