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 };
  • 相关阅读:
    botzone Tetris2
    NOIP2017游记
    城乡联谊胡策会糊厕R3
    SRM 20
    AtCoder Regular Contest 082
    AtCoder Grand Contest 019
    复数模版
    SRM13
    NOI2017&&codeM2017游记
    java多线程编程
  • 原文地址:https://www.cnblogs.com/chkkch/p/2742987.html
Copyright © 2011-2022 走看看