数据结构中的二叉搜索树
二叉搜索树是一种具有某些属性的二叉树。这些属性如下 −
- 每个二叉搜索树都是一棵二叉树
- 每个左孩子都比父节点小
- 每个右孩子都比父节点大
- 理想的二叉搜索树不会保存相同的值两次。
假设我们有这样一棵树 −
这棵树是一棵二叉搜索树。它遵循上面提到的所有属性。如果我们按照中序遍历模式遍历元素,我们可以得到 5、8、10、15、16、20、23。让我们看一段代码,了解如何在 C++ 代码中实现这一目标。
示例
#include<iostream> using namespace std; class node{ public: int h_left, h_right, bf, value; node *left, *right; }; class tree{ private: node *get_node(int key); public: node *root; tree(){ root = NULL; //set root as NULL at the beginning } void inorder_traversal(node *r); node *insert_node(node *root, int key); }; node *tree::get_node(int key){ node *new_node; new_node = new node; //create a new node dynamically new_node->h_left = 0; new_node->h_right = 0; new_node->bf = 0; new_node->value = key; //store the value from given key new_node->left = NULL; new_node->right = NULL; return new_node; } void tree::inorder_traversal(node *r){ if(r != NULL){ //When root is present, visit left - root - right inorder_traversal(r->left); cout << r->value << " "; inorder_traversal(r->right); } } node *tree::insert_node(node *root, int key){ if(root == NULL){ return (get_node(key)); //when tree is empty, create a node as root } if(key < root->value){ //when key is smaller than root value, go to the left root->left = insert_node(root->left, key); }else if(key > root->value){ //when key is greater than root value, go to the right root->right = insert_node(root->right, key); } return root; //when key is already present, do not insert it again } main(){ node *root; tree my_tree; //Insert some keys into the tree. my_tree.root = my_tree.insert_node(my_tree.root, 10); my_tree.root = my_tree.insert_node(my_tree.root, 5); my_tree.root = my_tree.insert_node(my_tree.root, 16); my_tree.root = my_tree.insert_node(my_tree.root, 20); my_tree.root = my_tree.insert_node(my_tree.root, 15); my_tree.root = my_tree.insert_node(my_tree.root, 8); my_tree.root = my_tree.insert_node(my_tree.root, 23); cout << "In-Order Traversal: "; my_tree.inorder_traversal(my_tree.root); }
输出
In-Order Traversal: 5 8 10 15 16 20 23
广告