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

二.我的解题思路

树的问题,往往很容易想到递归的解法。判断一个树是不是平衡二叉树,只要判断它的左右子树是否是平衡二叉树即可,依次递归下去。只要发现某课子树不平衡,那么整个树一定是不平衡的。我设计的递归函数有两个参数,一个是指向树节点的指针,一个表示当前有没有遇到非平衡子树的res变量,如果res==-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 {
public:
    bool isBalanced(TreeNode* root) {
        if (!root) return 1;
        int res = 0;
        int left_height = gen_height(root->left, res);
        int right_height = gen_height(root->right, res);
        if (res == -1) return 0;
        if(abs(left_height - right_height) > 1) return 0;
        else return 1;
        
    }
    
    int gen_height(TreeNode* root, int& res ){
        if(res == -1) return 0;
        if(!root) return 0;
        int left_height = gen_height(root->left, res);
        int right_height = gen_height(root->right, res);
        if(abs(left_height - right_height) > 1) res = -1;
        return (left_height>right_height)?left_height+1:right_height+1;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值