Complete Binary Search Tree

本博客的代码的思想和图片参考:好大学慕课浙江大学陈越老师、何钦铭老师的《数据结构》 

Complete Binary Search Tree

1 Question


A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.
Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.
Sample Input:
10
1 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
时间限制:400ms
内存限制:64MB
代码长度限制:16kB
判题程序:系统默认
作者:陈越
单位:浙江大学

 

2 Question Analysis


2.1 How to Choose Data Structure


There are two data structures to choose, array or link list. How to choose them. Let us to analysis the question requests.
First the question requests search the array or link list and put elements in it array and link list can do it easily.
 Second the question need to level search binary tree. Array just need to print element in order but link list need a queue to implement this function.
Third we use the complete tree, we just need to store elements in order in array, don’t need to use link list.
In a word, we choose the array as the data structures

 


2.2 Algorithm Thoughts


2.2.1 Analysis the Input


We know from the question, input is the a  N distinct non-negative integer keys. For complete binary tree, if we know N, we can determine the unique binary tree we want. So the result work it how to put elements into the binary tree.


2.2.2 Find Root Element


We can reference complete tree’s attributes to query how many left nodes(L) and how many right nodes(N) if given total nodes. At this moment we need to sort elements from smaller to greater in given array. So we can get the root element’s index is L +start index in given input data array. Then we recursive use this method to complete sub left tree and sub right tree until all elements be put into the complete binary search tree.

 

2.2.3 How to Calculate the quantity of sub tress 





The Code is followed:



  1 /*
  2  * completeBinarySearchTree.c
  3  *
  4  *  Created on: 2017年5月10日
  5  *      Author: ygh
  6  */
  7 
  8 /*
  9  * Algorithm thoughts:
 10  * 1.We use the array to store the complete binary search tree
 11  * 2.We will sort the data ascending given in form of a integer array
 12  * 3.We can get a binary tree sub left nodes and sub right nodes by calculating
 13  * 4.The root element index in given data array is startIndex + left nodes
 14  * 5.Call same method for sub left tree and sub right tree recursive
 15  */
 16 
 17 #include <stdio.h>
 18 #include <stdlib.h>
 19 #include <math.h>
 20 
 21 /*
 22  * Give a tree with n nodes,calculate how many left nodes it has
 23  * @param n The total nodes the tree has.
 24  * @return A integer number of the left tree nodes
 25  */
 26 int calculateLeftTreeLength(int n) {
 27     int h, x, l;
 28     h = log2(n + 1);
 29     x = n + 1 - pow(2, h);
 30     if (x > pow(2, h - 1)) {
 31         x = pow(2, h - 1);
 32     }
 33     l = pow(2, h - 1) - 1 + x;
 34     return l;
 35 }
 36 
 37 /*
 38  * A function to put the input array elements to complete
 39  * the initialized condition is (0,n-1,0,tree[],array[])
 40  * binary search tree
 41  * @param aLeft The complete binary search tree data start index in input array
 42  * @param aLeft The complete binary search tree data end index in input array
 43  * @param tRoot The index of the complete binary search tree root
 44  * @param tree A array to store complete binary search tree.
 45  * @param array A array store the input data and has been sorted ascending
 46  */
 47 void solve(int aLeft, int aRight, int tRoot, int *tree, int *array) {
 48     /*
 49      * n:the total nodes of the tree
 50      * letfLength:the nodes of the sub left nodes
 51      * leftRoot:the index of the sub left root in the tree
 52      * rightRoot:the index of the sub right root in the tree
 53      */
 54     int n, leftLength, leftRoot, rightRoot;
 55     /*
 56      * Get the all nodes of the tree
 57      */
 58     n = aRight - aLeft + 1;
 59     if(n==0){
 60         return;
 61     }
 62     leftLength = calculateLeftTreeLength(n);
 63     tree[tRoot] = array[aLeft + leftLength];
 64     leftRoot = tRoot * 2 + 1;
 65     rightRoot = leftRoot + 1;
 66     solve(aLeft, aLeft + leftLength - 1, leftRoot, tree, array);
 67     solve(aLeft + leftLength + 1, aRight, rightRoot, tree, array);
 68 }
 69 
 70 void getInputData(int length, int *array) {
 71     int data, i;
 72     for (i = 0; i < length; i++) {
 73         scanf("%d", &data);
 74         array[i] = data;
 75     }
 76 }
 77 
 78 void levelSearch(int *tree, int length) {
 79     int i;
 80     for (i = 0; i < length; i++) {
 81         if (i == length - 1) {
 82             printf("%d", tree[i]);
 83         } else {
 84             printf("%d ", tree[i]);
 85         }
 86     }
 87 }
 88 
 89 /*
 90  * A method to compare tow integer number
 91  */
 92 int compare(const void *a, const void *b) {
 93     return *(int*) a - *(int*) b;
 94 }
 95 
 96 int main() {
 97     int maxLength = 1000;
 98     int array[maxLength];
 99     int tree[maxLength];
100     int n;
101     scanf("%d", &n);
102     getInputData(n, array);
103     qsort(array, n, sizeof(int), compare);
104     solve(0, n - 1, 0, tree, array);
105     levelSearch(tree, n);
106     return 0;
107 }
Complete Binary Search Tree

PTA test result:

 

转载于:https://www.cnblogs.com/yghjava/p/6837826.html

构造一个完整的二叉搜索树(Complete Binary Search Tree, CBST)涉及两个关键方面:一是确保该树是一个完全二叉树,二是满足二叉搜索树的性质。 ### 完全二叉树的特点 完全二叉树是指除最后一层外,其余每一层都被完全填充,并且所有节点都必须尽可能靠左排列。这一特征使得我们可以有效地通过数组来表示完全二叉树,其中对于任意索引i处的节点: - 其左孩子位于位置2*i+1- 右孩子则处于位置2*i+2; ### 构建步骤概述 给定一组数值元素如列表`[7, 4, 9, 1, 5, 8, 10]`, 我们希望将其组织成一颗CBST: #### 步骤一: 对输入数据排序 首先应对原始序列进行升序排序得到 `[1, 4, 5, 7, 8, 9, 10]` #### 步骤二: 利用分治法递归生成CBST 采用类似堆排序的方式,找到中间点作为根节点(root),左侧部分构成左子树,右侧形成右子树。 例如选取上述排好序后的中间值 `7` 设为root,则左边 `[1, 4, 5]` 成为其左子树,右边 `[8, 9, 10]` 继续按同样规则处理直至每个叶节点均创建完毕为止。 ```python class TreeNode: def __init__(self, val=0): self.val = val self.left = None self.right = None def sortedArrayToBST(nums): if not nums: return None mid = len(nums) // 2 #取整数向下找中心位置 root = TreeNode(nums[mid]) root.left = sortedArrayToBST(nums[:mid]) #递归建立左半边树 root.right = sortedArrayToBST(nums[mid+1:]) #递归建立右半边树 return root ``` 这个Python示例程序展示了如何把已排序好的数组转换成为一棵平衡CBST的基本逻辑框架。 --- 如果您还有更多疑问或需要深入探讨某些细节,请随时提问!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值