@bintou
2017-12-07T23:00:58.000000Z
字数 7097
阅读 1772
Source
Code
本程序用于展示BST的基本操作,特别是使用Stack的遍历方法,让初学者建立直观。适合大一新生阅读。C语言为主。附加了一个Python代码,感觉Python代码非常简洁,个人非常喜欢,就推荐推荐。
// C program to demonstrate delete operation in binary search tree
#include<stdio.h>
#include<stdlib.h>
#include<stack.h>
// A utility function to create a new BST node
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
/* A utility function to insert a new node with given key in BST */
struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
/* return the (unchanged) node pointer */
return node;
}
/* Given a non-empty binary search tree, return the node with minimum
key value found in that tree. Note that the entire tree does not
need to be searched. */
struct node *minValueNode(struct node *node)
{
struct node* current = node;
/* loop down to find the leftmost leaf */
while (current->left != NULL)
current = current->left;
return current;
}
/* Given a binary search tree and a key, this function deletes the key
and returns the new root */
struct node *deleteNode(struct node *root, int key)
{
// base case
if (root == NULL) return root;
// If the key to be deleted is smaller than the root's key,
// then it lies in left subtree
if (key < root->key)
root->left = deleteNode(root->left, key);
// If the key to be deleted is greater than the root's key,
// then it lies in right subtree
else if (key > root->key)
root->right = deleteNode(root->right, key);
// if key is same as root's key, then This is the node
// to be deleted
else
{
// node with only one child or no child
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
// node with two children: Get the inorder successor (smallest
// in the right subtree)
struct node* temp = minValueNode(root->right);
// Copy the inorder successor's content to this node
root->key = temp->key;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
return root;
}
/* Iterative function for inorder tree traversal */
void Ite_inOrder(struct node *root)
{
/* set current to root of binary tree */
struct node *current = root;
struct Stack *stack = createStack(100);
bool done = 0;
while (!done)
{
/* Reach the left most tNode of the current tNode */
if(current != NULL)
{
/* place pointer to a tree node on the stack before traversing
the node's left subtree */
push(stack, current);
current = current->left;
}
/* backtrack from the empty subtree and visit the tNode
at the top of the stack; however, if the stack is empty,
you are done */
else
{
if (!isEmpty(stack))
{
current = pop(stack);
printf("%d ", current->key);
/* we have visited the node and its left subtree.
Now, it's right subtree's turn */
current = current->right;
}
else
done = 1;
}
} /* end of while */
}
// Driver Program to test above functions
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
struct node *root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
printf("Inorder traversal of the given tree \n");
inorder(root);
printf("\nDelete 20\n");
root = deleteNode(root, 20);
printf("Iteratively Inorder traversal of the modified tree \n");
Ite_inOrder(root);
printf("\n");
/*
printf("\nDelete 30\n");
root = deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n");
inorder(root);
printf("\nDelete 50\n");
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n");
inorder(root);
*/
return 0;
}
// C program for array implementation of stack
/*
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
Peek or Top: Returns top element of stack.
isEmpty: Returns true if stack is empty, else fals.
*/
#define bool int
//A structure to represent a tree
struct node
{
int key;
struct node *left, *right;
};
// A structure to represent a stack
struct Stack
{
int top;
int capacity;
struct node **array;
};
// function to create a stack of given capacity. It initializes size of
// stack as 0
struct Stack *createStack(unsigned capacity);
// Stack is full when top is equal to the last index
int isFull(struct Stack *stack);
// Stack is empty when top is equal to -1
int isEmpty(struct Stack *stack);
// Function to add an item to stack. It increases top by 1
void push(struct Stack *stack, struct node *item);
// Function to remove an item from stack. It decreases top by 1
struct node *pop(struct Stack *stack);
// C program for array implementation of stack
/*
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
Peek or Top: Returns top element of stack.
isEmpty: Returns true if stack is empty, else fals.
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stack.h>
// function to create a stack of given capacity. It initializes size of
// stack as 0
struct Stack* createStack(unsigned capacity)
{
struct Stack *stack = (struct Stack*) malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (struct node **) malloc(stack->capacity * sizeof(struct node *));
return stack;
}
// Stack is full when top is equal to the last index
int isFull(struct Stack *stack)
{ return stack->top == stack->capacity - 1; }
// Stack is empty when top is equal to -1
int isEmpty(struct Stack *stack)
{ return stack->top == -1; }
// Function to add an item to stack. It increases top by 1
void push(struct Stack *stack, struct node *item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
//printf("%d pushed to stack\n", item);
}
// Function to remove an item from stack. It decreases top by 1
struct node* pop(struct Stack *stack)
{
if (isEmpty(stack))
return NULL;
return stack->array[stack->top--];
}
# Python program to demonstrate insert operation in binary search tree
# A utility class that represents an individual node in a BST
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
# A utility function to insert a new node with the given key
def insert(root,node):
if root is None:
root = node
else:
if root.val < node.val:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert(root.left, node)
# A utility function to do inorder tree traversal
def inorder(root):
if root:
inorder(root.left)
print(root.val),
inorder(root.right)
# Iterative function for inorder tree traversal
def Ite_inOrder(root):
#set current to root of binary tree
current = root
stack = []
done = False
while not done:
# Reach the left most tNode of the current tNode
if current != None:
#place pointer to a tree node on the stack before traversing the node's left subtree
stack.append(current)
current = current.left
# backtrack from the empty subtree and visit the tNode
# at the top of the stack; however, if the stack is empty,
# you are done
else:
if len(stack) != 0:
current = stack.pop()
print(current.val),
# we have visited the node and its left subtree.
# Now, it's right subtree's turn
current = current.right
else:
done = True
# end of while
#end of Ite_inOrder
# Driver program to test the above functions
# Let us create the following BST
# 50
# / \
# 30 70
# / \ / \
# 20 40 60 80
r = Node(50)
insert(r,Node(30))
insert(r,Node(20))
insert(r,Node(40))
insert(r,Node(70))
insert(r,Node(60))
insert(r,Node(80))
# Print inoder traversal of the BST
inorder(r)
# This code is contributed by Bhavya Jain
Ite_inOrder(r)
# Ite_inOrder is contributed by Bintou