http://oj.leetcode.com/problems/balanced-binary-tree/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int isBalancedDepth(TreeNode *root){
if(root==NULL) return 0;
int left=isBalancedDepth(root->left);
int right=isBalancedDepth(root->right);
if(left<0||right<0) return -1;
if(abs(left-right)>1) return -1;
return max(left,right)+1;
}
bool isBalanced(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
return isBalancedDepth(root)>=0;
}
};
本文介绍了一种用于判断二叉树是否为平衡二叉树的递归算法。该算法通过计算每个节点的左右子树深度,并确保任意两个相邻子树的深度差不超过1来实现。文中提供了一个名为Solution的类,其中包括isBalancedDepth和isBalanced两个核心方法。
106

被折叠的 条评论
为什么被折叠?



