Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.
confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.
OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.
Here’s an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as “{1,2,3,#,#,4,#,#,5}”.
题意:判断一棵树是否满足二叉搜索树。
二叉搜索树的特点:左子树<根节点<右子树
解题思路:中序遍历,链栈,来实现。
对于一颗二叉树,中序遍历的结果若满足递增排序就满足二叉搜索树的条件,例如:
一颗二叉树如下:
中序遍历的结果如下:1234567
正好满足二叉搜索树的条件,所以本题采用中序遍历的思路,把遍历的结果存储于链栈中,通过比较前后存入链栈的大小,来判断是否为二叉搜索树。
实现C代码如下:
/**
*解题思路:中序遍历,链栈
* Definition for binary tree
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int flag;
struct Node{//创建一个链栈节点
int val;
struct Node *next;
};
struct Stack{//创建一个链栈
struct Node *top;//指向链栈栈顶节点
int count;//记录链栈的节点个数
};
void InitStack(struct Stack *stack){//初始化一个空栈
stack->count = 0;
stack->top = NULL;
}
void PushStack(struct Stack *stack,int val){//压栈
struct Node *node;
node = (struct Node *)malloc(sizeof(struct Node));
if(stack->count > 0){
if(stack->top->val < val){//若不是第一个进栈的节点,则判断与栈顶节点的值大小,若小于栈顶节点值则说明不是二叉搜索树
node->val = val;
node->next = stack->top;
stack->top = node;
stack->count++;
}else{
flag = -1;//若不是二叉搜索树设置全局标志位flag为-1;
return;
}
}else{//第一个值进栈
node->val = val;
node->next = stack->top;
stack->top = node;
stack->count++;
}
}
void Inorder(struct TreeNode *root,struct Stack *stack){//中序遍历
if(root == NULL){
return;
}
Inorder(root->left,stack);
PushStack(stack,root->val);
Inorder(root->right,stack);
}
bool isValidBST(struct TreeNode *root) {
flag = 0;
struct Stack *stack;
stack = (struct Stack *)malloc(sizeof(struct Stack));
InitStack(stack);
Inorder(root,stack);
if(flag == -1){
return 0;
}
return 1;
}