按照层次序列创建二叉树,并判断二叉树是否为二叉搜索树
首先定义树节点的数据结构,如下:
struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; };
两个函数,用来创建节点,以及构建树的,这个树的构建,我们采用最简单的按层次结构构造。通过一个先入先出队列,来存储节点的左右叶子节点。
struct TreeNode * createTreeNode(int val) { struct TreeNode* node = malloc(sizeof(struct TreeNode)); if (node != NULL) { node->val = val; node->left = NULL; node->right = NULL; return node; } return NULL }
#define MAXNODE 100
struct TreeNode * createBiTree(int *BiNum, int size) { struct TreeNode * Queue[MAXNODE] = {0}; int front = -1; int rear = 0; struct TreeNode *node; struct TreeNode *leftNode; struct TreeNode *rightNode; int i = 0; if (BiNum != NULL) node = createTreeNode(BiNum[i]); if (node) Queue[rear] = node; i++; while(i < size && rear != front) { leftNode = createTreeNode(BiNum[i]); front++; Queue[front]->left = leftNode; if (leftNode) { rear++; Queue[rear] = leftNode; } i++; if (i < size) { rightNode = createTreeNode(BiNum[i]); Queue[front]->right = rightNode; if (rightNode) { rear++; Queue[rear] = rightNode; } i++; } } return node; }
最后我们写一个函数,来判定此二叉树是否为搜索二叉树。判断一颗树是否是二叉搜索树,一棵树是BST需要满足
- 一个节点的值大于它左子树所有节点的值
- 一个节点的值小于它右子树所有节点的值
- 左右子树也必须是二叉搜索树
所以只需要遍历每个节点,判断
- 该节点值是否大于左子树的最大值
- 该节点值是否小于右子树的最小值
bool isValidBST(struct TreeNode* root){ struct TreeNode* leftnode; struct TreeNode* rightnode; if (root == NULL) return true; leftnode = root->left; while(leftnode) { if (root->val <= leftnode->val) return false; leftnode = leftnode->right; } rightnode = root->right; while(rightnode) { if (root->val >= rightnode->val) return false; rightnode = rightnode->left; } if (isValidBST(root->left) && isValidBST(root->right)) return true; return false; }
最后来看下我们如何应用这些函数,给定一个数组{5,3,7,2,4,5,8,1};用层次顺序来组成一个二叉树,然后判断改树是否为一个二叉搜索树。
void main() { int num[8] = {5,3,7,2,4,6,8,1}; struct TreeNode * node = createBiTree(num, 8); printf("is valid BST %d", isValidBST(node)); }