[leetcode]Validate Binary Search Tree (判斷有效二叉搜尋樹 C語言實現)
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;
}