这种写法,效率比较高,每一个节点只访问一次。
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth = 0;
return isBalanceTree(pRoot,depth);
}
/* 后序遍历,这样每一个节点,只访问一次 */
bool isBalanceTree(TreeNode* pRoot, int& depth)
{
if(pRoot == NULL)
{
depth = 0;
return true;
}
int left = 0;
int right = 0;
if(isBalanceTree(pRoot->left,left) && isBalanceTree(pRoot->right,right))
{
int deff = left - right;
if(deff <= 1 && deff >= -1)
{
depth = left > right ? left : right;
depth += 1;
return true;
}
}
return false;
}
};