根据给定的先序遍历构造 BST - 在 C++ 中设置 1
c++server side programmingprogramming更新于 2024/10/2 19:12:00
假设我们有一个先序遍历。从这个遍历中,我们必须生成树,所以如果遍历像 [10, 5, 1, 7, 40, 50],那么树将像 −
为了解决这个问题,我们将使用这个技巧。这个技巧是为每个节点设置一个范围 {min...max}。首先,我们将范围初始化为 {INT_MIN...INT_MAX}。第一个节点肯定会在范围内,所以之后我们将创建根节点。要构建左子树,请将范围设置为 {INT_MIN… root->data}。如果值在范围 {INT_MIN… root->data} 内,则该值是左子树的一部分。要构建右子树,请将范围设置为 {root->data… max… INT_MAX}。
示例
#include <iostream> using namespace std; class node { public: int data; node *left; node *right; }; node* getNode (int data) { node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp; } node* makeTreeUtil( int pre[], int* preord_index, int key, int min, int max, int size ) { if( *preord_index >= size ) return NULL; node* root = NULL; if( key > min && key < max ){ root = getNode( key ); *preord_index += 1; if (*preord_index < size){ root->left = makeTreeUtil( pre, preord_index, pre[*preord_index], min, key, size ); root->right = makeTreeUtil( pre, preord_index, pre[*preord_index],key, max, size ); } } return root; } node *makeTree (int pre[], int size) { int preord_index = 0; return makeTreeUtil( pre, &preord_index, pre[0], INT_MIN, INT_MAX, size ); } void inord (node* node) { if (node == NULL) return; inord(node->left); cout << node->data << " "; inord(node->right); } int main () { int pre[] = {10, 5, 1, 7, 40, 50}; int size = sizeof( pre ) / sizeof( pre[0] ); node *root = makeTree(pre, size); cout << "中序遍历:"; inord(root); }
输出
中序遍历:1 5 7 10 40 50