1. 程式人生 > >判斷一棵樹是否為二叉搜尋樹

判斷一棵樹是否為二叉搜尋樹

演算法:使用BFS,在每次入隊前判斷是否滿足BST條件。程式碼:
#include <iostream>
#include <queue>
using namespace std;
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) {
if(pRoot == NULL)
return true;
queue<TreeNode
*>q;
q.push(pRoot);
while(!q.empty()){
TreeNode *tmp = q.front();
if(tmp->left!=NULL){
if(tmp->val < tmp->left->val)
return false;
else
q.push(tmp->left);
}
if(tmp->right!=NULL){
if(tmp->val > tmp->right->val)
return false;
else
q.push(tmp->right);
}
q.pop();
}
return true
;
}
};
int main() {
TreeNode *root= new TreeNode(1);
TreeNode *r1l = new TreeNode(2);
TreeNode *r1r = new TreeNode(3);
TreeNode *r2l = new TreeNode(4);
TreeNode *r2r = new TreeNode(5);
root->left = r1l;
root->right = r1r;
r1l->left = r2l;
r1l->right = r2r;
vector<vector<int>>res;
Solution
s;
cout<<s.IsBalanced_Solution(root)<< endl;
return 0;
}