The pre-order (or post-order) of the known binary search tree (BST) traverses the array to reconstruct the BST

Know the preorder of BST to traverse the array to reconstruct BST

#include <iostream>
#include <vector>
using namespace std;

struct TreeNode {
    
    
	TreeNode* left;
	TreeNode* right;
	int date;
	TreeNode(int value) :
		date(value), left(nullptr), right(nullptr)
	{
    
     }
};

void preTraversal(TreeNode* root) {
    
    
	if (root == nullptr) {
    
    
		return;
	}
	cout << root->date << " ";
	preTraversal(root->left);
	preTraversal(root->right);
	delete root;
}

TreeNode* buildBSTree(vector<int>& pre, int left, int right) {
    
    
	if (pre.empty() || left < 0 || right < 0 || right < left) {
    
    
		return nullptr;
	}
	int mid = left + 1;
	while (mid <= right && pre.at(mid) < pre.at(left)) {
    
    
		mid++;
	}
	TreeNode* root = new TreeNode(pre.at(left));
	root->left = buildBSTree(pre, left + 1, mid - 1);
	root->right = buildBSTree(pre, mid, right);
	return root;
}

int main() {
    
    
	vector<int> pre{
    
     5, 2, 1, 3, 8, 7, 9 };
	TreeNode* root = buildBSTree(pre, 0, pre.size() - 1);
	preTraversal(root);
	cout << endl;
	system("pause");
	return 0;
}

time complexity:

  • Worst case: O(N^2)
  • Best case: O(N*logN)

It is known that the post-order of BST traverses the array to reconstruct BST

#include <iostream>
#include <vector>
using namespace std;

struct TreeNode {
    
    
	TreeNode* left;
	TreeNode* right;
	int date;
	TreeNode(int value) :
		date(value), left(nullptr), right(nullptr)
	{
    
     }
};

void postTraversal(TreeNode* root) {
    
    
	if (root == nullptr) {
    
    
		return;
	}
	postTraversal(root->left);
	postTraversal(root->right);
	cout << root->date << " ";
	delete root;
}

TreeNode* buildBSTree(vector<int>& post, int left, int right) {
    
    
	if (post.empty() || right < 0 || left < 0 || right < left) {
    
    
		return nullptr;
	}
	int mid = left;
	while (post.at(mid) < post.at(right)) {
    
    
		mid++;
	}
	TreeNode* root = new TreeNode(post.at(right));
	root->left = buildBSTree(post, left, mid - 1);
	root->right = buildBSTree(post, mid, right - 1);
	return root;
}

int main() {
    
    
	vector<int> post{
    
     1, 3, 2, 7, 9, 8, 5 };
	TreeNode* root = buildBSTree(post, 0, post.size() - 1);
	postTraversal(root);
	cout << endl;
	system("pause");
	return 0;
}

time complexity:

  • Worst case: O(N^2)
  • Best case: O(N*logN)

If there is any infringement, please contact to delete it. If there is an error, please correct me, thank you

Guess you like

Origin blog.csdn.net/xiao_ma_nong_last/article/details/105663959