[英]Binary search tree from pre-order traversal and information about left and right nodes
Need to validate if the given preorder traversal is a BST or not?需要验证给定的前序遍历是否是 BST? The input that is file that contains a preorder traversal of a binary tree and also if the node has left, right, both or no children.输入是包含二叉树的先序遍历的文件,以及节点是否有左、右、两个或没有子节点。 For example例如
-2 3
-4 3
-5 0
-3 0
2 3
0 3
-1 0
1 0
5 1
4 0
means that "-2" node has both left and right children.意味着“-2”节点有左右孩子。 "-5" has no children. “-5”没有孩子。 Basically基本上
0 -> no children
1 -> right child
2 -> left child
3 -> both Children
this is the node structure which cannot be modified这是无法修改的节点结构
typedef struct _Tnode {
int key;
int height;
struct _Tnode *left;
struct _Tnode *right;
} Tno
PS: In this example it is not a BST. PS:在这个例子中它不是 BST。 The tree which I could construct out of this looks like this我可以用它构建的树看起来像这样
-2
/ \
/ \
-4 2
/ \ / \
-5 -3 0 5
/ \ \
-1 1 4
You can use a recursive function to parse the input and check whether each value is within the acceptable range.您可以使用递归函数来解析输入并检查每个值是否在可接受的范围内。 It is not really needed to actually build the tree using the Tno
type:实际上并不需要使用Tno
类型来构建树:
#include <stdio.h>
#include <limits.h>
int isBST(min, max) {
int value, flags;
scanf("%d %d", &value, &flags);
if (value < min || value > max) return 0;
if ((flags > 1) && !isBST(min, value)) return 0;
if ((flags % 2 > 0) && !isBST(value, max)) return 0;
return 1;
}
int main(void) {
int result = isBST(INT_MIN, INT_MAX);
if (result) printf("This BST is fine\n");
else printf("Not a valid BST\n");
return 0;
}
If you need to build the tree, and only then verify whether it is a BST, then here is how you could do that:如果您需要构建树,然后才验证它是否是 BST,那么您可以这样做:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
typedef struct _Tnode {
int key;
int height;
struct _Tnode *left;
struct _Tnode *right;
} Tno;
Tno* createNode(int key) {
Tno* node = malloc(sizeof(Tno));
node->key = key;
node->left = node->right = NULL;
return node;
}
Tno* discardTree(Tno* node) {
if (node == NULL) return NULL;
discardTree(node->left);
discardTree(node->right);
free(node);
return NULL;
}
Tno* createTreeFromInput() {
int value, flags;
scanf("%d %d", &value, &flags);
Tno* node = createNode(value);
if (flags > 1) node->left = createTreeFromInput();
if (flags % 2 > 0) node->right = createTreeFromInput();
return node;
}
int isBST(Tno* node, int min) {
if (node == NULL) return min;
if (node->key < min) return INT_MAX; // Indication of error
min = isBST(node->left, min);
if (min > node->key) return INT_MAX;
return isBST(node->right, node->key);
}
int main(void) {
Tno* root = createTreeFromInput();
int ok = isBST(root, INT_MIN) < INT_MAX;
if (ok) printf("This BST is fine\n");
else printf("Not a valid BST\n");
discardTree(root);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.