用 C++ 從給定的前序遍歷構造 BST - 設定 1
假設我們有一個前序遍歷。從這個遍歷中。我們必須生成樹,所以如果遍歷像 [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 << "Inorder traversal: ";
inord(root);
}輸出
Inorder traversal: 1 5 7 10 40 50
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP