剑指 offer set 17 判断一棵树是否是平衡树

总结

1. 书上给出一个简洁代码, 说是会重复遍历.

2. 框架相同, 可以写出下面的代码

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;
    }
};

  

原文地址:https://www.cnblogs.com/xinsheng/p/3563882.html