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

二叉树定义:

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


我的思路是要判断整棵树是否平衡,先判断每个节点是否平衡。要判断每个节点是否平衡,就要求每个节点的左右子树是否高度在1以内。

关于二叉树的各种递归函数,我一般都是设置为void型。如果要求某种性质(如高度)或者判断某种条件(如是否平衡),我都会用一个变量(的引用)记录。

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        bool balanced = true;
        isTreeBalanced(root, balanced);
        return balanced;
    }
    
private:
    void isTreeBalanced(TreeNode *root, bool& balancedSofar) {   //  判断整棵树是否平衡
        if(root == NULL || !balancedSofar)
            return;
        
        if(!isNodeBalanced(root)) {
            balancedSofar = false;
            return;
        }
        isTreeBalanced(root->left, balancedSofar);
        isTreeBalanced(root->right, balancedSofar);
    }

    bool isNodeBalanced(TreeNode *root) {   //  判断节点是否平衡
        if(root == NULL)
            return true;
            
        int leftTreeDepth = 0;
        height(root->left, 1, leftTreeDepth);
        int rightTreeDepth = 0;
        height(root->right, 1, rightTreeDepth);
        
        if(leftTreeDepth-rightTreeDepth > 1 || rightTreeDepth - leftTreeDepth > 1)
            return false;
        else
            return true;
    }

	void height(TreeNode *root, int currentDepth, int& maxD) {  //  求树的高度(根为1)
		if (root == NULL)
			return;

		if (root->left == NULL && root->right == NULL && currentDepth > maxD) {  //  叶节点
			maxD = currentDepth;
			return;
		}
		height(root->left, currentDepth + 1, maxD);
		height(root->right, currentDepth + 1, maxD);
	}
};




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值