您的位置:首页 > 其它

validate binary search tree

2016-03-28 15:22 211 查看
二叉树 leetcode:

本题是关于给出的二叉树是否为BST树:

BST定义:

  对于任意一个parent节点,其leftchild node 小于 parent
  rightchild node 大于 parent节点

程序采用递归遍历:

#include <iostream>
#include <vector>

using namespace std;

struct TreeNode
{
int val;
TreeNode *l;
TreeNode *r;
TreeNode(int x) :val(x), l(nullptr), r(nullptr) {}
};

class Tree
{
private:
int n;
int n1;
TreeNode *temp[1000];
public:
TreeNode *Root;
Tree()
{
TreeNode *p;
int str[1000];
cout << "请输入数组的长度 n1 :";
cin >> n1;
cout << "请输入相应的元素:";
for (int i = 0; i < n1; i++)
cin >> str[i];
int parent = 1, child = 0;
n = 0;
for (int i = 0; i < n1; i++)
{
p = nullptr;
p = new TreeNode(str[i]);
}

child++;
temp[child] = p;
if (child == 1) { Root = p; }
else
{
if (p != nullptr && child % 2 == 0)
{
temp[parent]->l = p;
}

if (p != nullptr && child % 2 == 1)
{
temp[parent]->r = p;
}

if (child % 2 == 1)
{
parent++;
}
}
}

~Tree()
{
for (int i = 0; i < n1; i++)
{
if (temp[i] != nullptr)
delete temp[i];
}
}

bool IsvalidBST(TreeNode *t)
{
return isvalidBST(t, INT_MIN, INT_MAX);
}

bool isvalidBST(TreeNode *t, int left, int right)
{
if (t == nullptr) return true;
return t->val > left && t->val < right
&& isvalidBST(t->l, left, t->val)
&& isvalidBST(t->r, t->val, right);
}
};

int main()
{
Tree tree;
cout << endl;
cout << "此二叉树是否是BST:";
if (tree.IsvalidBST(tree.Root))
{
cout << "是" << endl;
}
else
{
cout << "否" << endl;
}

cout << endl;

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