[关闭]
@bintou 2017-12-07T23:00:58.000000Z 字数 7097 阅读 1831

Binary Search Tree

Source Code


本程序用于展示BST的基本操作,特别是使用Stack的遍历方法,让初学者建立直观。适合大一新生阅读。C语言为主。附加了一个Python代码,感觉Python代码非常简洁,个人非常喜欢,就推荐推荐。

BST操作

  1. // C program to demonstrate delete operation in binary search tree
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<stack.h>
  5. // A utility function to create a new BST node
  6. struct node *newNode(int item)
  7. {
  8. struct node *temp = (struct node *)malloc(sizeof(struct node));
  9. temp->key = item;
  10. temp->left = temp->right = NULL;
  11. return temp;
  12. }
  13. // A utility function to do inorder traversal of BST
  14. void inorder(struct node *root)
  15. {
  16. if (root != NULL)
  17. {
  18. inorder(root->left);
  19. printf("%d ", root->key);
  20. inorder(root->right);
  21. }
  22. }
  23. /* A utility function to insert a new node with given key in BST */
  24. struct node* insert(struct node* node, int key)
  25. {
  26. /* If the tree is empty, return a new node */
  27. if (node == NULL) return newNode(key);
  28. /* Otherwise, recur down the tree */
  29. if (key < node->key)
  30. node->left = insert(node->left, key);
  31. else
  32. node->right = insert(node->right, key);
  33. /* return the (unchanged) node pointer */
  34. return node;
  35. }
  36. /* Given a non-empty binary search tree, return the node with minimum
  37. key value found in that tree. Note that the entire tree does not
  38. need to be searched. */
  39. struct node *minValueNode(struct node *node)
  40. {
  41. struct node* current = node;
  42. /* loop down to find the leftmost leaf */
  43. while (current->left != NULL)
  44. current = current->left;
  45. return current;
  46. }
  47. /* Given a binary search tree and a key, this function deletes the key
  48. and returns the new root */
  49. struct node *deleteNode(struct node *root, int key)
  50. {
  51. // base case
  52. if (root == NULL) return root;
  53. // If the key to be deleted is smaller than the root's key,
  54. // then it lies in left subtree
  55. if (key < root->key)
  56. root->left = deleteNode(root->left, key);
  57. // If the key to be deleted is greater than the root's key,
  58. // then it lies in right subtree
  59. else if (key > root->key)
  60. root->right = deleteNode(root->right, key);
  61. // if key is same as root's key, then This is the node
  62. // to be deleted
  63. else
  64. {
  65. // node with only one child or no child
  66. if (root->left == NULL)
  67. {
  68. struct node *temp = root->right;
  69. free(root);
  70. return temp;
  71. }
  72. else if (root->right == NULL)
  73. {
  74. struct node *temp = root->left;
  75. free(root);
  76. return temp;
  77. }
  78. // node with two children: Get the inorder successor (smallest
  79. // in the right subtree)
  80. struct node* temp = minValueNode(root->right);
  81. // Copy the inorder successor's content to this node
  82. root->key = temp->key;
  83. // Delete the inorder successor
  84. root->right = deleteNode(root->right, temp->key);
  85. }
  86. return root;
  87. }
  88. /* Iterative function for inorder tree traversal */
  89. void Ite_inOrder(struct node *root)
  90. {
  91. /* set current to root of binary tree */
  92. struct node *current = root;
  93. struct Stack *stack = createStack(100);
  94. bool done = 0;
  95. while (!done)
  96. {
  97. /* Reach the left most tNode of the current tNode */
  98. if(current != NULL)
  99. {
  100. /* place pointer to a tree node on the stack before traversing
  101. the node's left subtree */
  102. push(stack, current);
  103. current = current->left;
  104. }
  105. /* backtrack from the empty subtree and visit the tNode
  106. at the top of the stack; however, if the stack is empty,
  107. you are done */
  108. else
  109. {
  110. if (!isEmpty(stack))
  111. {
  112. current = pop(stack);
  113. printf("%d ", current->key);
  114. /* we have visited the node and its left subtree.
  115. Now, it's right subtree's turn */
  116. current = current->right;
  117. }
  118. else
  119. done = 1;
  120. }
  121. } /* end of while */
  122. }
  123. // Driver Program to test above functions
  124. int main()
  125. {
  126. /* Let us create following BST
  127. 50
  128. / \
  129. 30 70
  130. / \ / \
  131. 20 40 60 80 */
  132. struct node *root = NULL;
  133. root = insert(root, 50);
  134. root = insert(root, 30);
  135. root = insert(root, 20);
  136. root = insert(root, 40);
  137. root = insert(root, 70);
  138. root = insert(root, 60);
  139. root = insert(root, 80);
  140. printf("Inorder traversal of the given tree \n");
  141. inorder(root);
  142. printf("\nDelete 20\n");
  143. root = deleteNode(root, 20);
  144. printf("Iteratively Inorder traversal of the modified tree \n");
  145. Ite_inOrder(root);
  146. printf("\n");
  147. /*
  148. printf("\nDelete 30\n");
  149. root = deleteNode(root, 30);
  150. printf("Inorder traversal of the modified tree \n");
  151. inorder(root);
  152. printf("\nDelete 50\n");
  153. root = deleteNode(root, 50);
  154. printf("Inorder traversal of the modified tree \n");
  155. inorder(root);
  156. */
  157. return 0;
  158. }

Stack的定义

  1. // C program for array implementation of stack
  2. /*
  3. Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
  4. 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.
  5. Peek or Top: Returns top element of stack.
  6. isEmpty: Returns true if stack is empty, else fals.
  7. */
  8. #define bool int
  9. //A structure to represent a tree
  10. struct node
  11. {
  12. int key;
  13. struct node *left, *right;
  14. };
  15. // A structure to represent a stack
  16. struct Stack
  17. {
  18. int top;
  19. int capacity;
  20. struct node **array;
  21. };
  22. // function to create a stack of given capacity. It initializes size of
  23. // stack as 0
  24. struct Stack *createStack(unsigned capacity);
  25. // Stack is full when top is equal to the last index
  26. int isFull(struct Stack *stack);
  27. // Stack is empty when top is equal to -1
  28. int isEmpty(struct Stack *stack);
  29. // Function to add an item to stack. It increases top by 1
  30. void push(struct Stack *stack, struct node *item);
  31. // Function to remove an item from stack. It decreases top by 1
  32. struct node *pop(struct Stack *stack);

Stack的实现

  1. // C program for array implementation of stack
  2. /*
  3. Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
  4. 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.
  5. Peek or Top: Returns top element of stack.
  6. isEmpty: Returns true if stack is empty, else fals.
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <limits.h>
  11. #include <stack.h>
  12. // function to create a stack of given capacity. It initializes size of
  13. // stack as 0
  14. struct Stack* createStack(unsigned capacity)
  15. {
  16. struct Stack *stack = (struct Stack*) malloc(sizeof(struct Stack));
  17. stack->capacity = capacity;
  18. stack->top = -1;
  19. stack->array = (struct node **) malloc(stack->capacity * sizeof(struct node *));
  20. return stack;
  21. }
  22. // Stack is full when top is equal to the last index
  23. int isFull(struct Stack *stack)
  24. { return stack->top == stack->capacity - 1; }
  25. // Stack is empty when top is equal to -1
  26. int isEmpty(struct Stack *stack)
  27. { return stack->top == -1; }
  28. // Function to add an item to stack. It increases top by 1
  29. void push(struct Stack *stack, struct node *item)
  30. {
  31. if (isFull(stack))
  32. return;
  33. stack->array[++stack->top] = item;
  34. //printf("%d pushed to stack\n", item);
  35. }
  36. // Function to remove an item from stack. It decreases top by 1
  37. struct node* pop(struct Stack *stack)
  38. {
  39. if (isEmpty(stack))
  40. return NULL;
  41. return stack->array[stack->top--];
  42. }

BST in Python

  1. # Python program to demonstrate insert operation in binary search tree
  2. # A utility class that represents an individual node in a BST
  3. class Node:
  4. def __init__(self,key):
  5. self.left = None
  6. self.right = None
  7. self.val = key
  8. # A utility function to insert a new node with the given key
  9. def insert(root,node):
  10. if root is None:
  11. root = node
  12. else:
  13. if root.val < node.val:
  14. if root.right is None:
  15. root.right = node
  16. else:
  17. insert(root.right, node)
  18. else:
  19. if root.left is None:
  20. root.left = node
  21. else:
  22. insert(root.left, node)
  23. # A utility function to do inorder tree traversal
  24. def inorder(root):
  25. if root:
  26. inorder(root.left)
  27. print(root.val),
  28. inorder(root.right)
  29. # Iterative function for inorder tree traversal
  30. def Ite_inOrder(root):
  31. #set current to root of binary tree
  32. current = root
  33. stack = []
  34. done = False
  35. while not done:
  36. # Reach the left most tNode of the current tNode
  37. if current != None:
  38. #place pointer to a tree node on the stack before traversing the node's left subtree
  39. stack.append(current)
  40. current = current.left
  41. # backtrack from the empty subtree and visit the tNode
  42. # at the top of the stack; however, if the stack is empty,
  43. # you are done
  44. else:
  45. if len(stack) != 0:
  46. current = stack.pop()
  47. print(current.val),
  48. # we have visited the node and its left subtree.
  49. # Now, it's right subtree's turn
  50. current = current.right
  51. else:
  52. done = True
  53. # end of while
  54. #end of Ite_inOrder
  55. # Driver program to test the above functions
  56. # Let us create the following BST
  57. # 50
  58. # / \
  59. # 30 70
  60. # / \ / \
  61. # 20 40 60 80
  62. r = Node(50)
  63. insert(r,Node(30))
  64. insert(r,Node(20))
  65. insert(r,Node(40))
  66. insert(r,Node(70))
  67. insert(r,Node(60))
  68. insert(r,Node(80))
  69. # Print inoder traversal of the BST
  70. inorder(r)
  71. # This code is contributed by Bhavya Jain
  72. print
  73. Ite_inOrder(r)
  74. # Ite_inOrder is contributed by Bintou
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注