
- 資料結構與演算法
- DSA - 首頁
- DSA - 概述
- DSA - 環境搭建
- DSA - 演算法基礎
- DSA - 漸近分析
- 資料結構
- DSA - 資料結構基礎
- DSA - 資料結構和型別
- DSA - 陣列資料結構
- 連結串列
- DSA - 連結串列資料結構
- DSA - 雙向連結串列資料結構
- DSA - 迴圈連結串列資料結構
- 棧與佇列
- DSA - 棧資料結構
- DSA - 表示式解析
- DSA - 佇列資料結構
- 搜尋演算法
- DSA - 搜尋演算法
- DSA - 線性搜尋演算法
- DSA - 二分搜尋演算法
- DSA - 插值搜尋
- DSA - 跳躍搜尋演算法
- DSA - 指數搜尋
- DSA - 斐波那契搜尋
- DSA - 子列表搜尋
- DSA - 雜湊表
- 排序演算法
- DSA - 排序演算法
- DSA - 氣泡排序演算法
- DSA - 插入排序演算法
- DSA - 選擇排序演算法
- DSA - 歸併排序演算法
- DSA - 希爾排序演算法
- DSA - 堆排序
- DSA - 桶排序演算法
- DSA - 計數排序演算法
- DSA - 基數排序演算法
- DSA - 快速排序演算法
- 圖資料結構
- DSA - 圖資料結構
- DSA - 深度優先遍歷
- DSA - 廣度優先遍歷
- DSA - 生成樹
- 樹資料結構
- DSA - 樹資料結構
- DSA - 樹遍歷
- DSA - 二叉搜尋樹
- DSA - AVL樹
- DSA - 紅黑樹
- DSA - B樹
- DSA - B+樹
- DSA - 伸展樹
- DSA - 字典樹
- DSA - 堆資料結構
- 遞迴
- DSA - 遞迴演算法
- DSA - 使用遞迴實現漢諾塔
- DSA - 使用遞迴實現斐波那契數列
- 分治法
- DSA - 分治法
- DSA - 最大最小問題
- DSA - Strassen矩陣乘法
- DSA - Karatsuba演算法
- 貪心演算法
- DSA - 貪心演算法
- DSA - 旅行商問題(貪心法)
- DSA - Prim最小生成樹
- DSA - Kruskal最小生成樹
- DSA - Dijkstra最短路徑演算法
- DSA - 地圖著色演算法
- DSA - 分數揹包問題
- DSA - 帶截止日期的作業排序
- DSA - 最優合併模式演算法
- 動態規劃
- DSA - 動態規劃
- DSA - 矩陣鏈乘法
- DSA - Floyd-Warshall演算法
- DSA - 0-1揹包問題
- DSA - 最長公共子序列演算法
- DSA - 旅行商問題(動態規劃法)
- 近似演算法
- DSA - 近似演算法
- DSA - 頂點覆蓋演算法
- DSA - 集合覆蓋問題
- DSA - 旅行商問題(近似演算法)
- 隨機化演算法
- DSA - 隨機化演算法
- DSA - 隨機化快速排序演算法
- DSA - Karger最小割演算法
- DSA - Fisher-Yates洗牌演算法
- DSA有用資源
- DSA - 問答
- DSA - 快速指南
- DSA - 有用資源
- DSA - 討論
二叉搜尋樹
二叉搜尋樹 (BST) 是一種樹,其中所有節點都遵循以下屬性:
節點的左子樹中的鍵小於或等於其父節點的鍵。
節點的右子樹中的鍵大於或等於其父節點的鍵。
因此,BST 將其所有子樹劃分為兩個部分:左子樹和右子樹,可以定義為:
left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)
二叉樹表示
BST 是以保持 BST 屬性的方式排列的節點的集合。每個節點都有一個鍵和一個關聯的值。在搜尋時,將所需的鍵與 BST 中的鍵進行比較,如果找到,則檢索關聯的值。
以下是 BST 的圖形表示:

我們觀察到根節點鍵 (27) 的左子樹包含所有值較小的鍵,右子樹包含所有值較大的鍵。
基本操作
以下是二叉搜尋樹的基本操作:
搜尋 - 在樹中搜索元素。
插入 - 在樹中插入元素。
前序遍歷 - 以預序方式遍歷樹。
中序遍歷 - 以中序方式遍歷樹。
後序遍歷 - 以後序方式遍歷樹。
定義節點
定義一個節點,它儲存一些資料以及對其左右子節點的引用。
struct node { int data; struct node *leftChild; struct node *rightChild; };
搜尋操作
每當要搜尋元素時,從根節點開始搜尋。如果資料小於鍵值,則在左子樹中搜索元素。否則,在右子樹中搜索元素。對每個節點遵循相同的演算法。
演算法
1. START 2. Check whether the tree is empty or not 3. If the tree is empty, search is not possible 4. Otherwise, first search the root of the tree. 5. If the key does not match with the value in the root, search its subtrees. 6. If the value of the key is less than the root value, search the left subtree 7. If the value of the key is greater than the root value, search the right subtree. 8. If the key is not found in the tree, return unsuccessful search. 9. END
示例
以下是此操作在各種程式語言中的實現:
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *leftChild, *rightChild; }; struct node *root = NULL; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = item; temp->leftChild = temp->rightChild = NULL; return temp; } void insert(int data){ struct node *tempNode = (struct node*) malloc(sizeof(struct node)); struct node *current; struct node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty if(root == NULL) { root = tempNode; } else { current = root; parent = NULL; while(1) { parent = current; //go to left of the tree if(data < parent->data) { current = current->leftChild; //insert to the left if(current == NULL) { parent->leftChild = tempNode; return; } }//go to right of the tree else { current = current->rightChild; //insert to the right if(current == NULL) { parent->rightChild = tempNode; return; } } } } } struct node* search(int data){ struct node *current = root; while(current->data != data) { //go to left tree if(current->data > data) { current = current->leftChild; }//else go to right tree else { current = current->rightChild; } //not found if(current == NULL) { return NULL; } } return current; } void printTree(struct node* Node){ if(Node == NULL) return; printTree(Node->leftChild); printf(" --%d", Node->data); printTree(Node->rightChild); } int main(){ insert(55); insert(20); insert(90); insert(50); insert(35); insert(15); insert(65); printf("Insertion done"); printf("\nBST: \n"); printTree(root); struct node* k; int ele = 35; printf("\nElement to be searched: %d", ele); k = search(35); if(k != NULL) printf("\nElement %d found", k->data); else printf("\nElement not found"); return 0; }
輸出
Insertion done BST: --15 --20 --35 --50 --55 --65 --90 Element to be searched: 35 Element 35 found
#include <iostream> using namespace std; struct Node { int data; struct Node *leftChild, *rightChild; }; Node *root = NULL; Node *newNode(int item){ Node *temp = (Node *)malloc(sizeof(Node)); temp->data = item; temp->leftChild = temp->rightChild = NULL; return temp; } void insert(int data){ Node *tempNode = (Node*) malloc(sizeof(Node)); Node *current; Node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty if(root == NULL) { root = tempNode; } else { current = root; parent = NULL; while(1) { parent = current; //go to left of the tree if(data < parent->data) { current = current->leftChild; //insert to the left if(current == NULL) { parent->leftChild = tempNode; return; } }//go to right of the tree else { current = current->rightChild; //insert to the right if(current == NULL) { parent->rightChild = tempNode; return; } } } } } Node* search(int data){ Node *current = root; while(current->data != data) { //go to left tree if(current->data > data) { current = current->leftChild; }//else go to right tree else { current = current->rightChild; } //not found if(current == NULL) { return NULL; } } return current; } void printTree(Node* Node) { if (Node == nullptr) return; printTree(Node->leftChild); cout << " --" << Node->data; printTree(Node->rightChild); } int main(){ insert(55); insert(20); insert(90); insert(50); insert(35); insert(15); insert(65); cout<<"Insertion done"; cout<<"\nBST: "<<endl; printTree(root); struct node* k; int ele = 35; cout<<"\nElement to be searched: "<<ele; Node* result = search(35); if(k != NULL) cout<<"\nElement "<<result->data<<" found "; else cout<<"\nElement not found"; return 0; }
輸出
Insertion done BST: --15 --20 --35 --50 --55 --65 --90 Element to be searched: 35 Element 35 found
import java.util.Scanner; class BSTNode { BSTNode left, right; int data; public BSTNode(int n) { left = null; right = null; data = n; } } public class BST { static BSTNode root; public BST() { root = null; } private BSTNode insert(BSTNode node, int data) { if(node == null) node = new BSTNode(data); else { if(data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); } return node; } private boolean search(BSTNode r, int val) { boolean found = false; while ((r != null) && !found) { int rval = r.data; if(val < rval) r = r.left; else if (val > rval) r = r.right; else { found = true; break; } found = search(r, val); } return found; } void printTree(BSTNode node, String prefix) { if(node == null) return; printTree(node.left , " " + prefix); System.out.print(prefix + "--" + node.data + " "); printTree(node.right , prefix); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); BST bst = new BST(); root = bst.insert(root, 55); root = bst.insert(root, 20); root = bst.insert(root, 90); root = bst.insert(root, 80); root = bst.insert(root, 50); root = bst.insert(root, 35); root = bst.insert(root, 15); root = bst.insert(root, 65); System.out.print("Insertion Done"); System.out.print("\nBST:\n"); bst.printTree(root, ""); int ele = 80; System.out.print("\nElement to be searched: " + ele); System.out.println("\nElement found: " + bst.search(root, 80)); } }
輸出
Insertion Done BST: --15 --20 --35 --50 --55 --65 --80 --90 Element to be searched: 80 Element found: true
class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert method to create nodes def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # search method to compare the value with nodes def search(self, key): if key < self.data: if self.left is None: return str(key)+" Not Found" return self.left.search(key) elif key > self.data: if self.right is None: return str(key)+" Not Found" return self.right.search(key) else: print(str(self.data) + ' is found') root = Node(54) root.insert(34) root.insert(46) root.insert(12) root.insert(23) root.insert(5) print(root.search(17)) print(root.search(12))
輸出
17 Not Found 12 is found None
插入操作
每當要插入元素時,首先找到其正確位置。從根節點開始搜尋,如果資料小於鍵值,則在左子樹中搜索空位置並插入資料。否則,在右子樹中搜索空位置並插入資料。
演算法
1. START 2. If the tree is empty, insert the first element as the root node of the tree. The following elements are added as the leaf nodes. 3. If an element is less than the root value, it is added into the left subtree as a leaf node. 4. If an element is greater than the root value, it is added into the right subtree as a leaf node. 5. The final leaf nodes of the tree point to NULL values as their child nodes. 6. END
示例
以下是此操作在各種程式語言中的實現:
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *leftChild, *rightChild; }; struct node *root = NULL; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = item; temp->leftChild = temp->rightChild = NULL; return temp; } void insert(int data){ struct node *tempNode = (struct node*) malloc(sizeof(struct node)); struct node *current; struct node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty if(root == NULL) { root = tempNode; } else { current = root; parent = NULL; while(1) { parent = current; //go to left of the tree if(data < parent->data) { current = current->leftChild; //insert to the left if(current == NULL) { parent->leftChild = tempNode; return; } }//go to right of the tree else { current = current->rightChild; //insert to the right if(current == NULL) { parent->rightChild = tempNode; return; } } } } } void printTree(struct node* Node){ if(Node == NULL) return; printTree(Node->leftChild); printf(" --%d", Node->data); printTree(Node->rightChild); } int main(){ insert(55); insert(20); insert(90); insert(50); insert(35); insert(15); insert(65); printf("Insertion done\n"); printf("BST: \n"); printTree(root); return 0; }
輸出
Insertion done BST: --15 --20 --35 --50 --55 --65 --90
#include <iostream> using namespace std; struct node { int data; struct node *leftChild, *rightChild; }; struct node *root = NULL; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = item; temp->leftChild = temp->rightChild = NULL; return temp; } void insert(int data){ struct node *tempNode = (struct node*) malloc(sizeof(struct node)); struct node *current; struct node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty if(root == NULL) { root = tempNode; } else { current = root; parent = NULL; while(1) { parent = current; //go to left of the tree if(data < parent->data) { current = current->leftChild; //insert to the left if(current == NULL) { parent->leftChild = tempNode; return; } }//go to right of the tree else { current = current->rightChild; //insert to the right if(current == NULL) { parent->rightChild = tempNode; return; } } } } } void printTree(struct node* Node){ if(Node == NULL) return; printTree(Node->leftChild); cout<<" --"<<Node->data; printTree(Node->rightChild); } int main(){ insert(55); insert(20); insert(90); insert(50); insert(35); insert(15); insert(65); cout<<"Insertion done\n"; cout<<"BST:"<<endl; printTree(root); return 0; }
輸出
Insertion done BST: --15 --20 --35 --50 --55 --65 --90
import java.util.Scanner; class BSTNode { BSTNode left, right; int data; public BSTNode(int n) { left = null; right = null; data = n; } } public class BST { static BSTNode root; public BST() { root = null; } private BSTNode insert(BSTNode node, int data) { if(node == null) node = new BSTNode(data); else { if(data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); } return node; } void printTree(BSTNode node, String prefix) { if(node == null) return; printTree(node.left , " " + prefix); System.out.print(prefix + "--" + node.data); printTree(node.right , prefix + " "); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); BST bst = new BST(); root = bst.insert(root, 55); root = bst.insert(root, 20); root = bst.insert(root, 90); root = bst.insert(root, 80); root = bst.insert(root, 50); root = bst.insert(root, 35); root = bst.insert(root, 15); root = bst.insert(root, 65); System.out.print("Insertion done\n"); System.out.print("BST:\n"); bst.printTree(root, " "); } }
輸出
Insertion done BST: --15 --20 --35 --50 --55 --65 --80 --90
class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert method to create nodes def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data def printTree(self, prefex): if self is None: return self.left.printTree(prefex + "") if self.left else None print(prefex + "--", str(self.data),"", end = "") self.right.printTree(prefex + "") if self.right else None root = Node(54) root.insert(34) root.insert(46) root.insert(12) root.insert(23) root.insert(5) print("Insertion Done") print("BST: ") root.printTree('')
輸出
Insertion Done BST: -- 5 -- 12 -- 23 -- 34 -- 46 -- 54
中序遍歷
二叉搜尋樹中的中序遍歷操作按以下順序訪問其所有節點:
首先,遍歷根節點/當前節點的左子節點(如果有)。
接下來,遍歷當前節點。
最後,遍歷當前節點的右子節點(如果有)。
演算法
1. START 2. Traverse the left subtree, recursively 3. Then, traverse the root node 4. Traverse the right subtree, recursively. 5. END
示例
以下是此操作在各種程式語言中的實現:
#include <stdio.h> #include <stdlib.h> struct node { int key; struct node *left, *right; }; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } // Inorder Traversal void inorder(struct node *root){ if (root != NULL) { inorder(root->left); printf("%d -> ", root->key); inorder(root->right); } } // Insertion operation struct node *insert(struct node *node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node; } int main(){ struct node *root = NULL; root = insert(root, 55); root = insert(root, 20); root = insert(root, 90); root = insert(root, 50); root = insert(root, 35); root = insert(root, 15); root = insert(root, 65); printf("Inorder traversal: "); inorder(root); }
輸出
Inorder traversal: 15 -> 20 -> 35 -> 50 -> 55 -> 65 -> 90 ->
#include <iostream> struct node { int key; struct node *left, *right; }; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } // Inorder Traversal void inorder(struct node *root){ if (root != NULL) { inorder(root->left); printf("%d -> ", root->key); inorder(root->right); } } // Insertion operation struct node *insert(struct node *node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node; } int main(){ struct node *root = NULL; root = insert(root, 55); root = insert(root, 20); root = insert(root, 90); root = insert(root, 50); root = insert(root, 35); root = insert(root, 15); root = insert(root, 65); printf("Inorder traversal: "); inorder(root); }
輸出
Inorder traversal: 15 -> 20 -> 35 -> 50 -> 55 -> 65 -> 90 ->
class Node { int data; Node leftChild; Node rightChild; public Node(int key) { data = key; leftChild = rightChild = null; } } public class TreeDataStructure { Node root = null; void inorder_traversal(Node node) { if(node != null) { inorder_traversal(node.leftChild); System.out.print(node.data + " ->"); inorder_traversal(node.rightChild); } } public static void main(String args[]) { TreeDataStructure tree = new TreeDataStructure(); tree.root = new Node(27); tree.root.leftChild = new Node(12); tree.root.rightChild = new Node(30); tree.root.leftChild.leftChild = new Node(4); tree.root.leftChild.rightChild = new Node(17); tree.root.rightChild.leftChild = new Node(56); System.out.println("Inorder traversal: "); tree.inorder_traversal(tree.root); } }
輸出
Inorder traversal: 4 ->12 ->17 ->27 ->56 ->30 ->
class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert method to create nodes def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # Print the tree def Inorder(self): if self.left: self.left.Inorder() print(self.data, "->", end = " ") if self.right: self.right.Inorder() root = Node(54) root.insert(34) root.insert(46) root.insert(12) root.insert(23) root.insert(5) print("Inorder Traversal: ") root.Inorder()
輸出
Inorder Traversal: 12 -> 34 -> 54 ->
前序遍歷
前序遍歷操作訪問二叉搜尋樹中的所有節點。但是,首先列印根節點,然後是其左子樹,最後是其右子樹。
演算法
1. START 2. Traverse the root node first. 3. Then traverse the left subtree, recursively 4. Later, traverse the right subtree, recursively. 5. END
示例
以下是此操作在各種程式語言中的實現:
#include <stdio.h> #include <stdlib.h> struct node { int key; struct node *left, *right; }; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } // Preorder Traversal void preorder(struct node *root){ if (root != NULL) { printf("%d -> ", root->key); preorder(root->left); preorder(root->right); } } // Insertion operation struct node *insert(struct node *node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node; } int main(){ struct node *root = NULL; root = insert(root, 55); root = insert(root, 20); root = insert(root, 90); root = insert(root, 50); root = insert(root, 35); root = insert(root, 15); root = insert(root, 65); printf("Preorder traversal: "); preorder(root); }
輸出
Preorder traversal: 55 -> 20 -> 15 -> 50 -> 35 -> 90 -> 65 ->
#include <iostream> struct node { int key; struct node *left, *right; }; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } // Preorder Traversal void preorder(struct node *root){ if (root != NULL) { printf("%d -> ", root->key); preorder(root->left); preorder(root->right); } } // Insertion operation struct node *insert(struct node *node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node; } int main(){ struct node *root = NULL; root = insert(root, 55); root = insert(root, 20); root = insert(root, 90); root = insert(root, 50); root = insert(root, 35); root = insert(root, 15); root = insert(root, 65); printf("Preorder traversal: "); preorder(root); }
輸出
Preorder traversal: 55 -> 20 -> 15 -> 50 -> 35 -> 90 -> 65 ->
class Node { int data; Node leftChild; Node rightChild; public Node(int key) { data = key; leftChild = rightChild = null; } } public class TreeDataStructure { Node root = null; void preorder_traversal(Node node) { if(node != null) { System.out.print(node.data + " ->"); preorder_traversal(node.leftChild); preorder_traversal(node.rightChild); } } public static void main(String args[]) { TreeDataStructure tree = new TreeDataStructure(); tree.root = new Node(27); tree.root.leftChild = new Node(12); tree.root.rightChild = new Node(30); tree.root.leftChild.leftChild = new Node(4); tree.root.leftChild.rightChild = new Node(17); tree.root.rightChild.leftChild = new Node(56); System.out.println("Preorder traversal: "); tree.preorder_traversal(tree.root); } }
輸出
Preorder traversal: 27 ->12 ->4 ->17 ->30 ->56 ->
class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert method to create nodes def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # Print the tree def Preorder(self): print(self.data, "->", end = "") if self.left: self.left.Preorder() if self.right: self.right.Preorder() root = Node(54) root.insert(34) root.insert(46) root.insert(12) root.insert(23) root.insert(5) print("Preorder Traversal: ") root.Preorder()
輸出
Preorder Traversal: 54 ->34 ->12 ->5 ->23 ->46 ->
後序遍歷
與其他遍歷一樣,後序遍歷也訪問二叉搜尋樹中的所有節點並顯示它們。但是,首先列印左子樹,然後是右子樹,最後是根節點。
演算法
1. START 2. Traverse the left subtree, recursively 3. Traverse the right subtree, recursively. 4. Then, traverse the root node 5. END
示例
以下是此操作在各種程式語言中的實現:
#include <stdio.h> #include <stdlib.h> struct node { int key; struct node *left, *right; }; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } // Postorder Traversal void postorder(struct node *root){ if (root != NULL) { printf("%d -> ", root->key); postorder(root->left); postorder(root->right); } } // Insertion operation struct node *insert(struct node *node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node; } int main(){ struct node *root = NULL; root = insert(root, 55); root = insert(root, 20); root = insert(root, 90); root = insert(root, 50); root = insert(root, 35); root = insert(root, 15); root = insert(root, 65); printf("Postorder traversal: "); postorder(root); }
輸出
Postorder traversal: 55 -> 20 -> 15 -> 50 -> 35 -> 90 > 65 ->
#include <iostream> struct node { int key; struct node *left, *right; }; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } // Postorder Traversal void postorder(struct node *root){ if (root != NULL) { printf("%d -> ", root->key); postorder(root->left); postorder(root->right); } } // Insertion operation struct node *insert(struct node *node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node; } int main(){ struct node *root = NULL; root = insert(root, 55); root = insert(root, 20); root = insert(root, 90); root = insert(root, 50); root = insert(root, 35); root = insert(root, 15); root = insert(root, 65); printf("Postorder traversal: "); postorder(root); }
輸出
Postorder traversal: 55 -> 20 -> 15 -> 50 -> 35 -> 90 -> 65 ->
class Node { int data; Node leftChild; Node rightChild; public Node(int key) { data = key; leftChild = rightChild = null; } } public class TreeDataStructure { Node root = null; void postorder_traversal(Node node) { if(node != null) { postorder_traversal(node.leftChild); postorder_traversal(node.rightChild); System.out.print(node.data + " ->"); } } public static void main(String args[]) { TreeDataStructure tree = new TreeDataStructure(); tree.root = new Node(27); tree.root.leftChild = new Node(12); tree.root.rightChild = new Node(30); tree.root.leftChild.leftChild = new Node(4); tree.root.leftChild.rightChild = new Node(17); tree.root.rightChild.leftChild = new Node(56); System.out.println("Postorder traversal: "); tree.postorder_traversal(tree.root); } }
輸出
Postorder traversal: 4 ->17 ->12 ->56 ->30 ->27 ->
class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert method to create nodes def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # Print the tree def Postorder(self): if self.left: self.left.Postorder() if self.right: self.right.Postorder() print(self.data, "->", end = "") root = Node(54) root.insert(34) root.insert(46) root.insert(12) root.insert(23) root.insert(5) print("Postorder Traversal: ") root.Postorder()
輸出
Postorder Traversal: 5 ->23 ->12 ->46 ->34 ->54 ->
完整實現
以下是二叉搜尋樹在各種程式語言中的完整實現:
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *leftChild, *rightChild; }; struct node *root = NULL; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = item; temp->leftChild = temp->rightChild = NULL; return temp; } void insert(int data){ struct node *tempNode = (struct node*) malloc(sizeof(struct node)); struct node *current; struct node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty if(root == NULL) { root = tempNode; } else { current = root; parent = NULL; while(1) { parent = current; //go to left of the tree if(data < parent->data) { current = current->leftChild; //insert to the left if(current == NULL) { parent->leftChild = tempNode; return; } }//go to right of the tree else { current = current->rightChild; //insert to the right if(current == NULL) { parent->rightChild = tempNode; return; } } } } } struct node* search(int data){ struct node *current = root; while(current->data != data) { if(current != NULL) { //go to left tree if(current->data > data) { current = current->leftChild; }//else go to right tree else { current = current->rightChild; } //not found if(current == NULL) { return NULL; } } } return current; } // Inorder Traversal void inorder(struct node *root){ if (root != NULL) { inorder(root->leftChild); printf("%d -> ", root->data); inorder(root->rightChild); } } // Preorder Traversal void preorder(struct node *root){ if (root != NULL) { printf("%d -> ", root->data); preorder(root->leftChild); preorder(root->rightChild); } } // Postorder Traversal void postorder(struct node *root){ if (root != NULL) { printf("%d -> ", root->data); postorder(root->leftChild); postorder(root->rightChild); } } int main(){ insert(55); insert(20); insert(90); insert(50); insert(35); insert(15); insert(65); printf("Insertion done"); printf("\nPreorder Traversal: "); preorder(root); printf("\nInorder Traversal: "); inorder(root); printf("\nPostorder Traversal: "); postorder(root); struct node* k; int ele = 35; printf("\nElement to be searched: %d", ele); k = search(35); if(k != NULL) printf("\nElement %d found", k->data); else printf("\nElement not found"); return 0; }
輸出
Insertion done Preorder Traversal: 55 -> 20 -> 15 -> 50 -> 35 -> 90 -> 65 -> Inorder Traversal: 15 -> 20 -> 35 -> 50 -> 55 -> 65 -> 90 -> Postorder Traversal: 55 -> 20 -> 15 -> 50 -> 35 -> 90 -> 65 -> Element to be searched: 35 Element 35 found
#include <iostream> using namespace std; struct node { int data; struct node *leftChild, *rightChild; }; struct node *root = NULL; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = item; temp->leftChild = temp->rightChild = NULL; return temp; } void insert(int data){ struct node *tempNode = (struct node*) malloc(sizeof(struct node)); struct node *current; struct node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty if(root == NULL) { root = tempNode; } else { current = root; parent = NULL; while(1) { parent = current; //go to left of the tree if(data < parent->data) { current = current->leftChild; //insert to the left if(current == NULL) { parent->leftChild = tempNode; return; } }//go to right of the tree else { current = current->rightChild; //insert to the right if(current == NULL) { parent->rightChild = tempNode; return; } } } } } struct node* search(int data){ struct node *current = root; while(current->data != data) { //go to left tree if(current->data > data) { current = current->leftChild; }//else go to right tree else { current = current->rightChild; } //not found if(current == NULL) { return NULL; } } return current; } // Inorder Traversal void inorder(struct node *root){ if (root != NULL) { inorder(root->leftChild); cout<<root->data<<" ->"; inorder(root->rightChild); } } // Preorder Traversala void preorder(struct node *root){ if (root != NULL) { cout<<root->data<<" ->"; preorder(root->leftChild); preorder(root->rightChild); } } // Postorder Traversal void postorder(struct node *root){ if (root != NULL) { cout<<" -> "<<root->data; postorder(root->leftChild); postorder(root->rightChild); } } int main(){ insert(55); insert(20); insert(90); insert(50); insert(35); insert(15); insert(65); cout<<"Insertion done "; cout<<"\nPreorder Traversal: "; preorder(root); cout<<"\nInorder Traversal: "; inorder(root); cout<<"\nPostorder Traversal: "; postorder(root); struct node* k; int ele = 35; cout<<"\nElement tonbe searched: "<<ele; k = search(35); if(k != NULL) cout<<"\nElement "<<k->data<<" found"; else cout<<"\nElement not found"; return 0; }
輸出
Insertion done Preorder Traversal: 55 ->20 ->15 ->50 ->35 ->90 ->65 -> Inorder Traversal: 15 ->20 ->35 ->50 ->55 ->65 ->90 -> Postorder Traversal: -> 55 -> 20 -> 15 -> 50 -> 35 -> 90 -> 65 Element tonbe searched: 35 Element 35 found
import java.util.Scanner; class BSTNode { BSTNode left, right; int data; public BSTNode(int n) { left = null; right = null; data = n; } } public class BST { static BSTNode root; public BST() { root = null; } public boolean isEmpty() { return root == null; } private BSTNode insert(BSTNode node, int data) { if(node == null) node = new BSTNode(data); else { if(data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); } return node; } public void delete(int k) { if(isEmpty ()) System.out.println("TREE EMPTY"); else if(search (k) == false) System.out.println("SORRY " + k + " IS NOT PRESENT"); else { root=delete(root,k); System.out.println(k + " DELETED FROM THE TREE"); } } public BSTNode delete(BSTNode root, int k) { BSTNode p, p2, n; if(root.data == k) { BSTNode lt, rt; lt = root.left; rt = root.right; if(lt == null && rt == null) { return null; } else if(lt == null) { p = rt; return p; } else if(rt == null) { p = lt; return p; } else { p2 = rt; p = rt; while(p.left != null) p = p.left; p.left = lt; return p2; } } if (k < root.data) { n = delete(root.left, k); root.left = n; } else { n = delete(root.right, k); root.right = n; } return root; } public boolean search(int val) { return search(root, val); } private boolean search(BSTNode r, int val) { boolean found = false; while ((r != null) && !found) { int rval = r.data; if(val < rval) r = r.left; else if (val > rval) r = r.right; else { found = true; break; } found = search(r, val); } return found; } void printTree(BSTNode node, String prefix) { if(node == null) return; printTree(node.left , " " + prefix); System.out.println(prefix + "--" + node.data); printTree(node.right , prefix + " "); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); BST bst = new BST(); root = bst.insert(root, 55); root = bst.insert(root, 20); root = bst.insert(root, 90); root = bst.insert(root, 80); root = bst.insert(root, 50); root = bst.insert(root, 35); root = bst.insert(root, 15); root = bst.insert(root, 65); bst.printTree(root, " "); bst.delete(55); System.out.println("Element found = " + bst.search(80)); System.out.println("Is Tree Empty? " + bst.isEmpty()); } }
輸出
--15 --20--35 --50 --55 --65 --80 --90 55 DELETED FROM THE TREE Element found = true Is Tree Empty? false
class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert method to create nodes def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # search method to compare the value with nodes def search(self, key): if key < self.data: if self.left is None: return str(key)+ " Not Found" return self.left.search(key) elif key > self.data: if self.right is None: return str(key)+" Not Found" return self.right.search(key) else: print(str(self.data) + ' is found') # Print the tree def Inorder(self): if self.left: self.left.Inorder() print(self.data , " ->", end = " ") if self.right: self.right.Inorder() # Print the tree def Preorder(self): print(self.data, " ->", end = " ") if self.left: self.left.Preorder() if self.right: self.right.Preorder() # Print the tree def Postorder(self): if self.left: self.left.Postorder() if self.right: self.right.Postorder() print(self.data, " ->", end = " ") root = Node(54) root.insert(34) root.insert(46) root.insert(12) root.insert(23) root.insert(5) print("Insertion Done") print("Preorder Traversal: ") root.Preorder() print("\nInorder Traversal: ") root.Inorder() print("\nPostorder Traversal: ") root.Postorder() ele = 17 print("\nElement to be searched: ", ele) print(root.search(ele))輸出
Insertion Done Preorder Traversal: 54 -> 34 -> 12 -> 5 -> 23 -> 46 -> Inorder Traversal: 5 -> 12 -> 23 -> 34 -> 46 -> 54 -> Postorder Traversal: 5 -> 23 -> 12 -> 46 -> 34 -> 54 -> Element to be searched: 17 17 Not Found