给定一个二叉树,判断此树是否为平衡二叉树。平衡二叉树,根节点的值小于右孩子节点的值,且大于左孩子节点的值。
递归方法:
bool isValidBST(TreeNode *root, TreeNode *&pre)
{
if (root == NULL)
return true;
if (!isValidBST(root->left, pre))
return false;
if (pre != NULL && pre->val >= root->val)
return false;
pre = root;
return isValidBST(root->right, pre);
}
bool isValidBST(TreeNode* root)
{
TreeNode *pre = NULL;
return isValidBST(root, pre);
}
非递归方法:中序遍历思想
bool isValidBST(TreeNode* root)
{
stack<TreeNode *> s;
TreeNode *pointer = root;
long long val = LLONG_MIN;
while (!s.empty() || pointer)
{
if (pointer)
{
s.push(pointer);
pointer = pointer->left;
}
else
{
pointer = s.top();
s.pop();
if (val >= pointer->val)
return false;
else
val = pointer->val;
pointer = pointer->right;
}
}
return true;
}