平衡二叉树
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
不是很懂, 一边递归一边判断, 可以消除节点遍历两次
class Solution {
public:
bool IsBalanced_Solution(TreeNode *pRoot, int *pDepth) {
if (nullptr == pRoot) {
*pDepth = 0;
return true;
}
int left = 0;
int right = 0;
if ((IsBalanced_Solution(pRoot->left, &left))
&& IsBalanced_Solution(pRoot->right, &right)) {
int dif = left - right;
if ((dif >= -1) && (dif <= 1)) {
*pDepth = 1 + (left > right ? left : right);
return true;
}
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth = 0;
return IsBalanced_Solution(pRoot, &depth);
}
};
递归判断布尔变量方法学学, 好像用到两次了, 节点遍历两次
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
int rightHigh = 1;
int leftHigh = 1;
if (nullptr == pRoot) {
return 0;
}
if (nullptr != pRoot->left) {
rightHigh += TreeDepth(pRoot->left);
}
if (nullptr != pRoot->right) {
leftHigh += TreeDepth(pRoot->right);
}
return rightHigh > leftHigh ? rightHigh : leftHigh;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if (nullptr == pRoot) {
return true;
}
int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);
int dif = left - right;
if (dif < -1 || dif >1) {
return false;
}
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
};