• 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.

    个人思路:

    1、判断每个节点(子树)的高度差,高度差在绝对值为1的范围内便是平衡二叉树

    2、可以适当改造计算树高度的方法,即树的高度为左子树与右子树高度较大者加1

    代码:

     1 #include <stddef.h>
     2 #include <iostream>
     3 /**
     4  * Definition for binary tree
     5  * struct TreeNode {
     6  *     int val;
     7  *     TreeNode *left;
     8  *     TreeNode *right;
     9  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    10  * };
    11  */
    12 
    13 struct TreeNode
    14 {
    15     int val;
    16     TreeNode *left;
    17     TreeNode *right;
    18     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    19 };
    20 
    21 class Solution
    22 {
    23 public:
    24     bool isBalanced(TreeNode *root)
    25     {
    26         balanced = true;
    27         getDepth(root);
    28 
    29         return balanced;
    30     }
    31     int getDepth(TreeNode *root)
    32     {
    33         if (root == NULL)
    34         {
    35             return 0;
    36         }
    37 
    38         int leftDepth = getDepth(root->left);
    39         int rightDepth = getDepth(root->right);
    40 
    41         if (leftDepth - rightDepth > 1 || leftDepth - rightDepth < -1)
    42         {
    43             balanced = false;
    44         }
    45 
    46         return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
    47     }
    48 private:
    49     bool balanced;
    50 };
    51 
    52 int main()
    53 {
    54     TreeNode *root = new TreeNode(1);
    55     root->right = new TreeNode(1);
    56     root->right->right = new TreeNode(1);
    57     Solution s;
    58     s.isBalanced(root);
    59     std::cout << root->val << std::endl << root->right->val << std::endl << root->right->val << std::endl;
    60     system("pause");
    61 
    62     return 0;
    63 }
    View Code

     上网搜了一些帖子,方法都是类似,就不贴出来了

  • 相关阅读:
    uva11572 Unique Snowflakes
    codeforces#333 div2 B. Approximating a Constant Range
    uva11134 Fabled Rooks
    吐槽。。。
    uva 1605 Building for UN
    uva 120 Stacks of Flapjacks
    uva1152 4 Values whose Sum is 0
    uva817 According to Bartjens
    uva11214 Guarding the Chessboard
    无标题
  • 原文地址:https://www.cnblogs.com/laihaiteng/p/3795408.html
Copyright © 2020-2023  润新知