Leetcode: Balanced Binary Tree

对每一个树节点, 判断其左右孩子的高度差, 一旦有一个不满足条件, 则返回 false

代码:

class Solution {
public:
	bool ans;
	int getHeight(TreeNode *root) {
		if(!ans)
			return 0;
		if(root == NULL)
			return 0;

		int lt = 0, rt = 0;
		if(root->left&&ans) {
			lt = 1+getHeight(root->left);
		}
		if(root->right&&ans)
			rt = 1 + getHeight(root->right);
		if(abs(lt-rt)>1)
			ans = false;
		return max(lt, rt);
	}
	
	bool isBalanced(TreeNode *root) {
        ans = true;
		if(root == NULL)
			return true;
		getHeight(root);
		return ans;
    }
};

  

posted @ 2013-12-05 15:04  SangS  阅读(440)  评论(0编辑  收藏  举报