您的位置:首页 > 其它

98.Validate Binary Search Tree&检查是否为BST

2015-06-29 11:35 295 查看
Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.

中序遍历二叉树,检查得到的序列是否是升序。

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {

public:
bool isValidBST(TreeNode* root) {
if(!root)
return true;
stack<TreeNode * > s;
TreeNode *p = root;
vector<int> ret;

while(p != 0 || !s.empty())
{
while(p != 0)
{
s.push(p);
p = p -> left;
}
if(!s.empty())
{
p = s.top();
ret.push_back(p -> val);
s.pop();
p = p -> right;

}
}
for(int i = ret.size() - 1;i>=1;i--)
{
if(ret[i] <= ret[i-1])
return false;
}
return true;

}
};


class Checker {
public:
bool checkBST(TreeNode* root) {
// write code here
if(!root)
return false;
vector<int> vals;
middleOrderNonRecurisive(root,vals);
for(int i = 0;i<vals.size()-1;++i)
{
if(vals[i] >= vals[i+1])
return false;
}
return true;

}

void middleOrderRecursive(TreeNode *root,vector<int> &vals)
{
if(root)
{
middleOrderRecursive(root->left,vals);
vals.push_back(root->val);
middleOrderRecursive(root->right,vals);
}
}

void middleOrderNonRecurisive(TreeNode *root,vector<int> &vals)
{
if(!root)
return;
stack<TreeNode *> pStack;

while(root || !pStack.empty())
{
while(root)
{
pStack.push(root);
root = root->left;
}
if(!pStack.empty())
{
root = pStack.top();
pStack.pop();
vals.push_back(root->val);
root = root->right;
}
}
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: