含有相同元素的二叉搜索树实现快速排序

写在前面

今天下午突然想到二叉树的中序遍历不就是升序的嘛,然后我就在OJ上找了一个n**2时间复杂度过不去的题目提交了自己的代码,竟然AC了!!不过效率不是很高,比归并排序略微慢点
下面直接贴代码

C++

#include <bits/stdc++.h>

using namespace std;
const int VERTICES = 1e5 + 10;
int a[VERTICES];

struct Node {
    int data;
    Node *left;
    Node *right;
};

struct Tree {
    Node *root;
};

void buildTree(Tree *tree, int value) {
    Node *node = (Node *) malloc(sizeof(Node));
    node->right = NULL;
    node->left = NULL;
    node->data = value;
    if (tree->root == NULL)
        tree->root = node;
    else {
        Node *temp = tree->root;
        while (temp != NULL) {
            if (value <= temp->data) {
                if (temp->left == NULL) {
                    temp->left = node;
                    return;
                } else
                    temp = temp->left;
            } else {
                if (temp->right == NULL) {
                    temp->right = node;
                    return;
                } else
                    temp = temp->right;
            }
        }
    }
}


void inorder(Node *node) {
    if (node == NULL)
        return;
    stack<Node *> st;
    Node *temp = node;
    while (!st.empty() || temp != NULL) {
        while (temp != NULL) {
            st.push(temp);
            temp = temp->left;
        }
        if (!st.empty()) {
            temp = st.top();
            printf("%d ", temp->data);
            st.pop();
            temp = temp->right;
        }
    }
}


int main() {
    int n;
    scanf("%d", &n);
    Tree tree;
    tree.root = NULL;
    for (int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
        buildTree(&tree, a[i]);
    }
    inorder(tree.root);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值