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.

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

代码实现

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        int  height = 0;
        return isBalancedCore(root,height); 
    }
    //这个辅助函数的参数部分额外的干了一件事,最终得到这棵树
    //的高度
    bool isBalancedCore(TreeNode* root,int & height){
        if(root == nullptr){
            height = 0;
            return true;
        }
        int  height1 = 0;
        int  height2 = 0;

        bool result = false;

        if(isBalancedCore(root->left,height1) && isBalancedCore(root->right,height2)){
            if(abs(height1 - height2) <= 1){
                height = max(height1,height2) + 1;
                result = true;
            }
        }
        return result;
    }
};

posted on 2021-06-14 07:08  朴素贝叶斯  阅读(17)  评论(0编辑  收藏  举报

导航