剑指 Offer 55 - II. 平衡二叉树

题目链接: leetcode.

暴力,计算每个节点的左右子树的深度

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
/*
执行用时:24 ms, 在所有 C++ 提交中击败了30.77%的用户
内存消耗:20.8 MB, 在所有 C++ 提交中击败了51.43%的用户
*/
class Solution {
public:
	int calDeep(TreeNode* root)
	{
		if(root == nullptr)
			return 0;
		return max(calDeep(root -> left), calDeep(root -> right)) + 1;
	}
    bool isBalanced(TreeNode* root) {
    	if(root == nullptr)//空树当然是平衡二叉树
    		return true;
        queue<TreeNode*> Q;
        Q.push(root);
        while(!Q.empty())
        {
        	TreeNode* node = Q.front();
        	Q.pop();
        	int t = calDeep(node -> left) - calDeep(node -> right);
        	if(t < -1 || t > 1)
        	{
        		return false;
        	}
        	//不要把空节点再放到队列里啦
            if(node -> left) 
        	    Q.push(node -> left);
            if(node -> right)
        	    Q.push(node -> right);
        }
        return true;
    }
};

写的太复杂了,,

二叉树的每个节点的左右子树的高度差的绝对值不超过1,则二叉树是平衡二叉树。根据定义,一棵二叉树是平衡二叉树,当且仅当其所有子树也都是平衡二叉树。
因此可以使用递归的方式判断二叉树是不是平衡二叉树

自顶向下 O(n^2) O(n)

class Solution {
public:
    int height(TreeNode* root) {
        if (root == NULL) {
            return 0;
        } else {
            return max(height(root->left), height(root->right)) + 1;
        }
    }

    bool isBalanced(TreeNode* root) {
        if (root == NULL) {
            return true;
        } else {
            return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
        }
    }
};

//作者:LeetCode-Solution
//链接:https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/
//来源:力扣(LeetCode)
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

自底向上 不用重复算树的深度了
O(n) O(n)

/*
执行用时:12 ms, 在所有 C++ 提交中击败了90.46%的用户
内存消耗:20.2 MB, 在所有 C++ 提交中击败了97.17%的用户
*/
class Solution {
public:
    int height(TreeNode* root) {
        if(root == nullptr)
        	return 0;
        int h_left = height(root -> left);
        int h_right = height(root -> right);
        if(h_left == -1 || h_right == -1)
        	return -1;
        if(abs(h_left - h_right) > 1)
        	return -1;
        return max(h_left, h_right) + 1;
    }

    bool isBalanced(TreeNode* root) {
        if (root == NULL) {
            return true;
        return height(root) != -1; 
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值