[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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章