@bintou
2017-12-07T15:00:58.000000Z
字数 7097
阅读 2370
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 nodestruct 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 BSTvoid 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);elsenode->right = insert(node->right, key);/* return the (unchanged) node pointer */return node;}/* Given a non-empty binary search tree, return the node with minimumkey value found in that tree. Note that the entire tree does notneed 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 keyand returns the new root */struct node *deleteNode(struct node *root, int key){// base caseif (root == NULL) return root;// If the key to be deleted is smaller than the root's key,// then it lies in left subtreeif (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 subtreeelse 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 deletedelse{// node with only one child or no childif (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 noderoot->key = temp->key;// Delete the inorder successorroot->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 traversingthe node's left subtree */push(stack, current);current = current->left;}/* backtrack from the empty subtree and visit the tNodeat 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;}elsedone = 1;}} /* end of while */}// Driver Program to test above functionsint main(){/* Let us create following BST50/ \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 treestruct node{int key;struct node *left, *right;};// A structure to represent a stackstruct Stack{int top;int capacity;struct node **array;};// function to create a stack of given capacity. It initializes size of// stack as 0struct Stack *createStack(unsigned capacity);// Stack is full when top is equal to the last indexint isFull(struct Stack *stack);// Stack is empty when top is equal to -1int isEmpty(struct Stack *stack);// Function to add an item to stack. It increases top by 1void push(struct Stack *stack, struct node *item);// Function to remove an item from stack. It decreases top by 1struct 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 0struct 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 indexint isFull(struct Stack *stack){ return stack->top == stack->capacity - 1; }// Stack is empty when top is equal to -1int isEmpty(struct Stack *stack){ return stack->top == -1; }// Function to add an item to stack. It increases top by 1void 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 1struct 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 BSTclass Node:def __init__(self,key):self.left = Noneself.right = Noneself.val = key# A utility function to insert a new node with the given keydef insert(root,node):if root is None:root = nodeelse:if root.val < node.val:if root.right is None:root.right = nodeelse:insert(root.right, node)else:if root.left is None:root.left = nodeelse:insert(root.left, node)# A utility function to do inorder tree traversaldef inorder(root):if root:inorder(root.left)print(root.val),inorder(root.right)# Iterative function for inorder tree traversaldef Ite_inOrder(root):#set current to root of binary treecurrent = rootstack = []done = Falsewhile not done:# Reach the left most tNode of the current tNodeif current != None:#place pointer to a tree node on the stack before traversing the node's left subtreestack.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 doneelse: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 turncurrent = current.rightelse: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 80r = 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 BSTinorder(r)# This code is contributed by Bhavya JainIte_inOrder(r)# Ite_inOrder is contributed by Bintou