zoukankan      html  css  js  c++  java
  • 构建一颗完全二叉搜索树

          给出一串数,如何来构造一颗完全二叉搜索树。我们了解完全二叉搜索树的定义,就不多说。接下来我们需要用一种数据结构来储存,一般使用线性表或者链表来储存一颗树,对于完全二叉树而言,用数组储存的优势高于用链表储存,对于线性表储存完全二叉数,不用担心空间的浪费,也容易操作。于是我们就选择线性表来储存。

    对于给定的一个一组数如:1 6 2 3  4 5,我们先对数做一次排序:1 2 3 4 5 6  .我们知道对于一个给定结点个数的完全二叉树就是一个固定形状的二叉树,左子树的数都比根节点小,右子树数都比根结点大。一旦知道左子树的结点个数我们就可以确定根节点的位置。对于上面给出的案例,首先这棵树的左子树有3个结点,于是根节点是第4位,即为4.于是1 2 3是左子树,4 5是右子树,然后用相同的方法去处理左子树和右子树,可以得到求解此问题的递归函数。

    #include<iostream>
    #include<fstream>
    #include<cmath>
    #include<algorithm>
    using namespace std;
    #define max 100
    class Tree{
    public:
    int a[max];
    int last;
    };
    Tree*T=new Tree; //建立一颗空的二叉搜索树
    void CreateBinaryT(int p[],int left,int right,int TRoot);
    int main(){
    ifstream sin("a.txt");
    int n,i;
    int p[max];
    while (sin >>n){
    T->last = n;
    for (i = 0; i < n; i++)
    sin >> p[i];
    sort(p, p + n);
    CreateBinaryT(p, 0, n - 1,0); //树的根节点在下标为0的位置开始
    for (i = 0; i < T->last; i++)
    cout << T->a[i] << " "; //层序输出
    cout << endl;
    }
    return 0;
    }
    int Getleftson(int n){/*此函数计算左子树结点个数*/
    int l, h, i;
    for (i = 0; pow(2, i) <= n; i++);
    h = i - 1;; //计算log(n+1)的下届
    l = n + 1 - pow(2, h);
    if (l>pow(2, h - 1))
    return pow(2, h) - 1;
    else
    return n - pow(2, h - 1);
    }
    void CreateBinaryT(int p[], int left, int right,int TRoot){
    int n = right - left + 1;
    if (n == 0)
    return; //p中没有元素要处理是递归出口
    int l = Getleftson(right - left + 1); //获得左子树节点个数
    T->a[TRoot] = p[left + l];
    CreateBinaryT(p, left, left + l - 1,TRoot*2+1); //左子树递归
    CreateBinaryT(p, left + l + 1, right,TRoot*2+2); //右子树递归
    }

  • 相关阅读:
    leetcode 1301. 最大得分的路径数目
    LeetCode 1306 跳跃游戏 III Jump Game III
    LeetCode 1302. 层数最深叶子节点的和 Deepest Leaves Sum
    LeetCode 1300. 转变数组后最接近目标值的数组和 Sum of Mutated Array Closest to Target
    LeetCode 1299. 将每个元素替换为右侧最大元素 Replace Elements with Greatest Element on Right Side
    acwing 239. 奇偶游戏 并查集
    acwing 238. 银河英雄传说 并查集
    acwing 237程序自动分析 并查集
    算法问题实战策略 MATCHORDER 贪心
    Linux 安装Redis全过程日志
  • 原文地址:https://www.cnblogs.com/td15980891505/p/4977923.html
Copyright © 2011-2022 走看看