二叉搜索树插入结点运行结果
结果分析
第一种算法用递归实现二叉树结点插入,思路简单,但是容易溢栈。
根据二叉查找树的定义,若插入节点的值若大于当前节点的值,则继续与当前节点的右子树的值进行比较;反之则继续与当前节点的左子树的值进行比较。
第二种迭代法比较当前节点的值和插入节点的值,到了二叉树的最后一层时选择是链接至左子结点还是右子节点。
两种算法的时间复杂度
二叉排序树的构造过程其实是n次插入,而一次插入中主要的运算在于查找。最坏情况下,每次插入的节点都是叶子节点,也就是说O(logn)。那么,构造整个二叉树,就有n次这样的查找,共计O(nlogn)。
本次实验的数据是100 *100 个数据结点,从上述截图可以看出迭代法优于递归。
实验代码
#include <iostream>
#include <time.h>
#include <stdlib.h>
#define MAX 100*100
#define MAXI 100000
using namespace std;
class TreeNode {
public:
int val;
TreeNode *left, *right;
TreeNode(int val){
this->val = val;
this->left = this->right = NULL;
}
TreeNode(){
this->left = this->right = NULL;
}
};
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree.
*/
//递归形式
TreeNode* insertNode(TreeNode* root, TreeNode* node) {
if (NULL == root) {
return node;
}
if (node->val <= root->val) {
root->left = insertNode(root->left, node);
} else {
root->right = insertNode(root->right, node);
}
return root;
}
//迭代形式
TreeNode* insertNode2(TreeNode* root, TreeNode* node) {
if (NULL == root) {
return node;
}
TreeNode* tempNode = root;
while (NULL != tempNode) {
if (node->val <= tempNode->val) {
if (NULL == tempNode->left) {
tempNode->left = node;
return root;
}
tempNode = tempNode->left;
} else {
if (NULL == tempNode->right) {
tempNode->right = node;
return root;
}
tempNode = tempNode->right;
}
}
return root;
}
void preTraverse(TreeNode* T)
{
if(T)
{
cout<<T->val<<" ";
preTraverse(T->left);
preTraverse(T->right);
}
}
};
void recursion(){
TreeNode root(0);
TreeNode *proot = &root; //指向根节点
TreeNode *node;
Solution so;
int start = clock();
for(int i=1; i<MAX; i++){
node = new TreeNode;
node->val = i;
so.insertNode(proot, node);
}
int end = clock();
int time = end - start;
cout<<"递归形式插入100*100有序结点耗时(ms):"<<time<<endl;
start = clock();
for(int i=1; i<MAX; i++){
node = new TreeNode;
node->val = rand();
so.insertNode(proot, node);
}
end = clock();
time = end - start;
cout<<"递归形式插入100*100无规律结点耗时(ms):"<<time<<endl;
// so.preTraverse(proot);
}
void iteration(){
TreeNode root(0);
TreeNode *proot = &root; //指向根节点
TreeNode *node;
Solution so;
int start = clock();
for(int i=1; i<MAX; i++){
node = new TreeNode;
node->val = i;
so.insertNode2(proot, node);
}
int end = clock();
int time = end - start;
cout<<"迭代形式插入100*100有序结点耗时(ms):"<<time<<endl;
start = clock();
for(int i=1; i<MAX; i++){
node = new TreeNode;
node->val = rand();
so.insertNode2(proot, node);
}
end = clock();
time = end - start;
cout<<"迭代形式插入100*100无规律结点耗时(ms):"<<time<<endl;
// so.preTraverse(proot);
}
int main(){
srand((unsigned int)time(NULL));
recursion();
iteration();
}