[Leetcode]110. 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,超过即为不平衡二叉树


[Leetcode]110. Balanced Binary Tree_第1张图片
例子

接下来放代码

解法一:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

// 我的方法为什么运行速度慢,因为我会把整棵树都遍历过去
class Solution {
 bool flagfind = false;
public:
    bool isBalanced(TreeNode* root) {
        maxDepth(root);
         if(flagfind == true) return false;   // 判断是否出现不平衡
        return true;
    }
public:
    int maxDepth(TreeNode* root){
        if(flagfind == true ) return 0   ;
        if( root == NULL ) return 1;
        int ldepth = maxDepth(root->left);
        int rdepth = maxDepth(root->right);
        if((ldepth-rdepth)<=1 && (ldepth-rdepth)>=-1) {
         //   cout<< "l:"<

自己写的代码AC后都没有说打败了多少人,因为运行时间真的太长了23333,于是看了一下别人的代码

解法二

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        int hgt = height(root);
        if(hgt == -1) {
            return false;
        }
        return true;
    }

private:
    int height(TreeNode* node) {        
        if(node == nullptr) return 0;      // Base case
        
        int leftHeight = height(node->left);        
        if(leftHeight == -1) return -1;    // 一旦出现不符合的,就不继续递归判断右边子树,这个地方比我少了一半时间,而我是一直左右都有判断,不需要,首先应当判断左子树,简化内容
        
        int rightHeight = height(node->right);        
        if(rightHeight == -1) return -1;
        
        int heightDiff = abs(leftHeight - rightHeight);
        if(heightDiff > 1) {              // 如果右边子树出现不平衡,返回-1,则左子树即使平衡,减去右子树一定大于1,
            return -1;
        }
        else {
            return 1 + max(leftHeight,rightHeight);
        }        
    }
};

注:abs()函数用来求绝对值
nullprt和NULL效果一样

你可能感兴趣的:([Leetcode]110. Balanced Binary Tree)