二進制搜索樹_將排序的數組轉換為二進制搜索樹

二進制搜索樹

Problem statement:

問題陳述:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

給定一個數組,其中元素按升序排序,請將其轉換為高度平衡的BST。

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

對于此問題,將高度平衡的二叉樹定義為一個二叉樹,其中每個節點的兩個子樹的深度相差不超過1。

Example:

例:

Let the sorted array to be:
[-1, 3, 6, 8]
The corresponding balanced BST is:
3
/   \
-1     6
\
8

Solution:

解:

The algorithm is simply finding the median in the sorted array and assigning it as a root. Then process the subtrees recursively.

該算法只是在排序后的數組中找到中位數并將其分配為根。 然后遞歸處理子樹。

Let the function to build the balanced BST from the sorted array is:

讓該函數根據排序后的數組構建平衡的BST:

buildBST() which has parameters: sorted array, lower index, higher index

buildBST()具有以下參數: 排序數組 , 較低索引 , 較高索引

has return type: TreeNode* // returns the root actually

具有返回類型: TreeNode * //實際上返回根

Function buildBST(sorted array, lower index , higher index)
1.  Base case:
IF lower index>higher index
Return NULL
2.  Declare middle index as (lower index + higher index)/2
3.  root=createnode(array[middle index]);
4.  Create the left subtree recursively
Root->left=buildBST(sorted array, lower index, middle index-1)
5.  Create the right subtree recursively
Root->left=buildBST(sorted array, middle index-1,higher index)
6.  Return root
END FUNCTION

In the main function we call,

在主函數中,我們稱之為

    Root=buildBST (sorted array, 0, size of array-1)

C++ implementation

C ++實現

#include <bits/stdc++.h>
using namespace std;
// TreeNode node type
class TreeNode{
public:             
int val;           //value
TreeNode *left;    //pointer to left child
TreeNode *right;   //pointer to right child
};
// creating new node
TreeNode* newnode(int data)  
{ 
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode)); 
node->val = data; 
node->left = NULL; 
node->right = NULL; 
return(node); 
}
TreeNode* buildBST(vector<int> nums,int low,int high){
if(low>high)
return NULL;
int mid=(low+high)/2;
TreeNode* root=newnode(nums[mid]); //creates new nodes
root->left=buildBST(nums,low,mid-1);
root->right=buildBST(nums,mid+1,high);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root=buildBST(nums,0,nums.size()-1);
return root;
}
void levelOrder(TreeNode* root) {
cout<<"root: \n";
queue<TreeNode*> q;
if(root==NULL){
cout<<"empty tree\n";
}
int count=1;		
TreeNode* temp;
q.push(root);
q.push(NULL);
while(!q.empty()){
temp=q.front();
q.pop();
if(temp==NULL){
if(!q.empty()){
cout<<"\nend of level: "<<count++<<endl;
q.push(NULL);
}
}
else{
cout<<temp->val<<" ";
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
}
cout<<"\nend of level: "<<count<<endl;
}
int main(){
int n,no;
cout<<"enter no of elements\n";
cin>>n;
vector<int> v;
cout<<"enter the sorted array\n";
while(n--){
cin>>no;
v.push_back(no);
}
TreeNode* root=sortedArrayToBST(v);
cout<<"displaying level order traversal\n";
levelOrder(root);
return 0;
}

Output

輸出量

enter no of elements
4
enter the sorted array
-1 3 6 8
displaying level order traversal
root:
3
end of level: 1
-1 6
end of level: 2
8
end of level: 3

Example with explanation

帶說明的例子

For simplicity all nodes are represented by its value
Let the sorted array to be:
A=-1, 3, 6, 8
So in the main function it calls:
Root=buildBST( A, 0, 3)
---------------------------------------------------
buildBST( A, 0, 3)
base case isn’t met
mid= 1
root= A[1]=3 
3->left=buildBST( A, 0, 0)
3->right= buildBST( A, 2, 3)
Return 3 (node)
---------------------------------------------------
buildBST( A, 0, 0)
base case isn’t met
mid= 0
root= A[0]=-1
-1->left=buildBST(A, 0, -1)
(-1)->right= buildBST(A, 1, 0)
Returns -1(node)
---------------------------------------------------
buildBST( A, 2, 3)
base case isn’t met
mid= 2
root= A[2]=6
6->left=buildBST(A, 2, 1)
(6)->right= buildBST(A, 3, 3)
Returns 6(node)
---------------------------------------------------
buildBST( A, 0, -1)
base case is met
Returns null
---------------------------------------------------
buildBST( A, 1, 0)
base case is met
Returns null
---------------------------------------------------
buildBST( A, 2, 1)
base case is met
Returns null
---------------------------------------------------
buildBST( A, 3, 3)
base case isn’t met
mid= 3
root= A[3]=8
8->left=buildBST(A, 3, 2)
(8)->right= buildBST(A, 4, 3)
Returns 8(node)
---------------------------------------------------
buildBST( A, 3, 2)
base case is met
Returns null
---------------------------------------------------
buildBST( A, 4, 3)
base case is met
Returns null
So,
8->left=NULL
8->right=NULL
6->left=NULL
6->right=8
-1->left=NULL
-1->right=NULL
3->left=-1
3->right=6
So the tree becomes:
3
/    \
-1       6
\
8

翻譯自: https://www.includehelp.com/icp/convert-sorted-array-to-binary-search-tree.aspx

二進制搜索樹

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/378983.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/378983.shtml
英文地址,請注明出處:http://en.pswp.cn/news/378983.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

rtmp協議分析(三次握手)

RTMP詳細分析(Message 消息&#xff0c;Chunk分塊) librtmp分析&#xff08;發送數據包處理&#xff09; librtmp分析&#xff08;接收數據包處理&#xff09; RTMP協議是Real Time Message Protocol(實時信息傳輸協議)的縮寫&#xff0c;它是由Adobe公司提出的一種應 用層的協…

OpenAPI系列: 六、OpenAPI策略分析

一、如何注冊 為什么要注冊&#xff1f;訪問 OpenAPI必須擁有Consumer Key和Consumer Secret。 如何注冊&#xff1f;要獲取Consumer Key及Consumer Secret&#xff0c;需要消費方&#xff08;Consumer&#xff09;向服務提供方申請注冊&#xff0c;服務提供方審核通過后會向消…

壓縮、解壓 解決 客戶端查詢大批量數據時等待時間過長的問題

在項目中查詢時&#xff0c;因數據量大&#xff0c;導致網絡傳輸很慢&#xff0c;這就需要在服務器端查詢出的數據進行壓縮處理&#xff0c;后傳輸完了在客戶端進行解壓處理&#xff08;此為在Silverlight中壓縮與解壓&#xff09;&#xff1b; 具體方法如下&#xff1a; using…

C---已知正整數n是兩個不同的質數的乘積,試求出較大的那個質數。

已知正整數n是兩個不同的質數的乘積&#xff0c;試求出較大的那個質數。 思路&#xff1a;由題意可知&#xff0c;n為兩個質數之積&#xff0c;也就是說只要找到一個數能夠被n整除&#xff0c;這個數一定是質數&#xff01;&#xff01;&#xff01;2為最小的質數&#xff0c;…

isnumeric_Python字符串| isnumeric()方法與示例

isnumericisnumeric() is an in-built method in Python, which is used to check whether a string contains only numeric values or not. isnumeric()是Python中的內置方法&#xff0c;用于檢查字符串是否僅包含數字值。 Numeric contain all decimal characters and the f…

合并文件夾中子目錄_01 Linux之統計文件夾中文件個數以及目錄個數

案例分析&#xff1a;今天遇到了一個需要統計路徑下目錄個數的問題如果一個一個的去數會很麻煩&#xff0c;找到了一篇文章剛好提到這個&#xff0c;于是我將方法整理了一下。該方法的鏈接&#xff1a;Linux統計文件夾中文件個數以及目錄個數_SG匚hang的博客-CSDN博客_linux統計…

關于Makefile,Makefile.in,Makefile.am,Configure功能及相互關系的問題

目錄makefile寫法1. 簡介2. 上路之前3. 一個簡單的例子4.說明&#xff1a;4.1、autoscan4.2、 configure.scan4.3、aclocal4.4、autoconf4.5、Makefile.am4.6、 automake4.7、Makefilemakefile寫法 在 Unix 上寫程式的人大概都碰過 Makefile&#xff0c;尤其是用 C 來開發程式…

修改主鍵的SQL

declare defname varchar(100)declare cmd varchar(500)declare tablename varchar(100)declare keyname varchar(100) Set tablenameTemp1Set keynameid --需要設置的key,分隔 select defname name FROM sysobjects so JOIN sysconstraints sc ON so.id sc.constid …

西安理工大學863(轉載)

原創&#xff1a;https://blog.csdn.net/mzj15101229871/article/details/107613162 &#xff08;博主總結的很完整&#xff0c;很厲害&#xff0c;本人為了查看方便&#xff0c;才轉載的。本人只是個小白~&#xff09; 第一章 緒論 考試大綱 1&#xff09;了解數據元素、數…

原理簡介_消息通信的利器MQTT協議簡介及協議原理

- 沒用過但是必須得知道系列 -前言&#xff1a;相比于 XMPP&#xff0c; MQTT 的簡單輕量受到了不少工程師的喜愛&#xff0c;從物聯網到傳統的消息服務&#xff0c;簡單可依賴的 MQTT 到底為何讓人如此著迷呢&#xff1f;MQTT 協議&#xff0d;MQTT 協議簡介及協議原理MQTT(Me…

stl vector 函數_vector :: pop_back()函數以及C ++ STL中的示例

stl vector 函數C vector :: pop_back()函數 (C vector::pop_back() function) vector::pop_back() is a library function of "vector" header, it is used to deletes an element from the end of the vector, it deletes the element from the back and returns …

rtmp協議分析(Message 消息,Chunk分塊)

RTMP詳細分析&#xff08;三次握手&#xff09; librtmp分析&#xff08;發送數據包處理&#xff09; librtmp分析&#xff08;接收數據包處理&#xff09; 目錄1、Message(消息)2、Chunking(Message 分塊)2.1、 Basic Header(基本的頭信息)2.1.1、Basic Header為1個字節時2.1.…

【文摘】 雪念——作者:藍色妖姬

引用原文地址&#xff1a;點我 我本是惆悵之人&#xff0c;擁有不了所謂的快樂&#xff0c;筆尖譜寫不出唯美的風花雪月&#xff0c;只是流露這淡淡的疼痛&#xff0c;淡淡的哀傷。——藍色妖姬。 喜歡雪&#xff0c;喜歡佇立在雪地里&#xff0c;凝視著片片雪花從眼前飄落。 心…

將Sharepoint Server 2010部署到WINDOWS 7

首先祝CNBLOGS上的筒子們新年快樂。Sharepoint 2010 BETA版發布已經有段時間了&#xff0c;總是感覺MS的步伐要比我們這些追逐他的人快很多&#xff0c;不過確實他的每一次革新總給我們帶來了驚喜。 前幾天報名參加了SHAREPOINT 2010 DAY 活動(詳情)&#xff0c;等待著1月16日體…

嵌入式實訓-day1

完全復制一個文件的內容到另外一個文件 思路解析&#xff1a; 首先我這里使用了三個.c文件&#xff0c;分別是&#xff1a;yanyu.c、yanyu_old.c、yanyu_now.c 其中yanyu.c負責將yanyu_old.c中的內容讀入到buff緩沖區中&#xff0c;然后再從buff緩沖區中將數據寫入到yanyu_no…

stl中copy()函數_std :: rotate_copy()函數以及C ++ STL中的示例

stl中copy()函數C STL std :: rotate_copy()函數 (C STL std::rotate_copy() function) rotate_copy() function is a library function of algorithm header, it is used to rotate left the elements of a sequence within a given range and copy the rotating elements to…

計量經濟學建模_淺談統計學模型(兼計量經濟學模型)

計量經濟學模型是從統計學模型中衍生出來的&#xff0c;故將它們一并放在此處進行說明。實際上&#xff0c;很多人在很久之前就督促我寫一篇統計學和計量經濟學模型的文章&#xff0c;但我太懶惰&#xff0c;一直拖到現在&#xff0c;也是十分汗顏。先講一些統計學上的基礎故事…

linux文件存儲、inode、硬鏈接、軟鏈接

目錄介紹inode的內容inode的大小inode號碼目錄文件硬鏈接軟鏈接介紹 文件儲存在硬盤上&#xff0c;硬盤的最小存儲單位叫做"扇區"&#xff08;Sector&#xff09;。每個扇區儲存512字節&#xff08;相當于0.5KB&#xff09;。操作系統讀取硬盤的時候&#xff0c;不會…

OSPF路由器建立全毗鄰關系的狀態轉換過程

1&#xff09;Down狀態&#xff1a;路由器不與其他任何路由器交換任何OSPF消息&#xff1b;2&#xff09;Init狀態&#xff1a;接收方路由器已經接收到對端路由器的hello包&#xff0c;但是沒有從對端路由器的hello包中發現自己的router-id.。此時通信是單向的&#xff1b;3&am…

JavaScript打包與解包工具

JavaScript Packer&#xff1a; http://packer.skiyo.cn/ JavaScript UnPacker&#xff1a; http://packer.skiyo.cn/unpacker.html 轉載于:https://www.cnblogs.com/springmvc-hibernate/archive/2010/09/17/2484233.html