[LeetCode]Balanced Binary Tree

题目:

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.


思路:

判断二叉平衡树。

写一个BalancedHeight 函数用来计算某一节点的高度,然后对当前节点求其左右子树的高度差,最后递归检查其左右子树是否平衡。

C++ AC代码:

/**
 * 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) {
        if ( root == NULL )
		    return true;
			
		if ( abs(BalancedHeight(root->left) - BalancedHeight(root->right)) > 1)
		    return false;
		return isBalanced(root->left) && isBalanced(root->right);
    }
	
	int BalancedHeight (TreeNode* root){
	    if ( root == NULL ) return 0;
		int left = BalancedHeight (root->left);
		int right = BalancedHeight (root->right);
		return 1+max(left,right); 
	}
};

运行时间 60ms

发布了55 篇原创文章 · 获赞 9 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章