validate binary search tree

二叉树 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值