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.

    Subscribe to see which companies asked this question

    不明白这个题为什么自己还是想了很久。

    改了很多,有的时候思路不明白还是写下来可以帮助自己理清头绪。

    就是求左子树的高度,右子树的高度,假如左子树减右子树的高度的绝对值大于2就不是平衡二叉树了,如果顶点满足要求,就要看左子树是否满足要求,然后右子树。

    不知道为什么写错了函数,写了一个专门求左子树高度的函数,专门求右子树的函数,脑子一定是被门夹了。

     1 #include<math.h>
     2 /**
     3  * Definition for a binary tree node.
     4  * struct TreeNode {
     5  *     int val;
     6  *     TreeNode *left;
     7  *     TreeNode *right;
     8  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     9  * };
    10  */
    11 class Solution {
    12 public:
    13     int maxDepth(TreeNode* root) {
    14         int lengthleft=0,lengthright=0;
    15         if (root==NULL) return 0;
    16         if (root->left == NULL && root->right == NULL){
    17             return 1;
    18         }
    19 
    20         if(root->left!=NULL){ 
    21             lengthleft=maxDepth(root->left)+1;
    22 
    23         }
    24         if(root->right!=NULL){
    25             lengthright=maxDepth(root->right)+1;
    26         }
    27             
    28         return lengthright>lengthleft?lengthright:lengthleft;
    29             
    30         }
    31     
    32     bool isBalanced(TreeNode* root) {
    33         if(root==NULL) return true;
    34         int m=maxDepth(root->left)-maxDepth(root->right);
    35         cout<<m<<endl;
    36         if(abs(m)<2) return isBalanced(root->left)&&isBalanced(root->right);
    37         else return false;
    38     }
    39     
    40 };
  • 相关阅读:
    Yougth的最大化(好题,二分查找 0 1分数规划)
    Cable master(好题,二分)
    Can you find it?(二分 二分+STL set map)
    Can you solve this equation?(二分)
    Bridging signals(二分 二分+stl dp)
    A Bug's Life
    Is It A Tree?(并查集)
    简单计算器(栈)
    Linux学习之常用压缩命令(三)
    Linux系统之常用文件搜索命令
  • 原文地址:https://www.cnblogs.com/LUO77/p/4987761.html
Copyright © 2011-2022 走看看