二进制搜索树

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)
.minHeight{ min-height: 250px; } @media (min-width: 1025px){ .minHeight{ min-height: 90px; } } .minHeight{ min-height: 250px; } @media (min-width: 1025px){ .minHeight{ min-height: 90px; } }

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
.minHeight{ min-height: 250px; } @media (min-width: 1025px){ .minHeight{ min-height: 90px; } } .minHeight{ min-height: 250px; } @media (min-width: 1025px){ .minHeight{ min-height: 90px; } }

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

二进制搜索树

二进制搜索树_将排序的数组转换为二进制搜索树相关推荐

  1. java整数转二进制字符串_在Java中将int转换为二进制字符串表示形式?

    AbbyPaden.. 5 这是我几分钟前刚写的东西.希望能帮助到你! public class Main { public static void main(String[] args) { Arr ...

  2. Suzy找到实习了吗 Day23 | 二叉树最后一节!669. 修剪二叉搜索树,108. 将有序数组转换为二叉搜索树,538. 把二叉搜索树转换为累加树

    669. 修剪二叉搜索树 题目 给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high.通过修剪二叉搜索树,使得所有节点的值在[low, high]中.修剪树 不应该 改变保 ...

  3. C++将01数组转换为二进制对应的数值

    假设有一个32维的01数组array,假设array的值为 01001010001011110100101000101111 如果需要将其转换为用该数组值代表的二进制所对应的数值,即通过该数组得到01 ...

  4. python如何把矩阵转换为图片_如何将numpy数组转换为(并显示)图片

    函数式编程 用python显示一张图片方法如下:import matplotlib.pyplot as plt # plt 用于显示图片import matplotlib.image as mpimg ...

  5. python 标量_只能将size-1数组转换为Python标量 - python

    我正在尝试练习python图像像素颜色直方图 import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imrea ...

  6. hdl四位二进制计数器_利用Quartus设计4位同步二进制加法计数器

    一.设计原理 4位同步二进制加法计数器的工作原理是指当时钟信号clk的上升沿到来时,且复位信号clr低电平有效时,就把计数器的状态清0. 在clr复位信号无效(即此时高电平有效)的前提下,当clk的上 ...

  7. ofstream 二进制 文本_使用ifstream和ofstream序列化二进制数据时遇到问题

    这是您的内容应如何阅读: #include #include #include struct SerializeTestStruct { char mCharVal; unsigned int mIn ...

  8. mysql 存储二进制数据_为什么在MySQL中存储二进制数据?

    I'm a little confused - what are the pros of storing binary data in DB? Is it for security reasons, ...

  9. C++十进制数转换为二进制表示的算法(附完整源码)

    C++十进制数转换为二进制表示的算法 C++十进制数转换为二进制表示的算法完整源码(定义,实现,main函数测试) C++十进制数转换为二进制表示的算法完整源码(定义,实现,main函数测试) #in ...

最新文章

  1. 如何删除Android上ListViews之间的行?
  2. RT-Thread的I/O设备模块及其驱动实现步骤
  3. 【Linux】【Services】【SaaS】Docker+kubernetes(13. 部署Jenkins/Maven实现代码自动化发布)...
  4. 【easysnmp】python snmp IF-MIB::ifPhysAddress messy code,解析mac地址乱码
  5. ISA2006标准版无人值守安装
  6. kmeans改进 matlab,基于距离函数的改进k―means 算法
  7. netflix 开源_Netflix的Polynote是一个新的开源框架,可用来构建更好的数据科学笔记本
  8. SpringCache与Redis
  9. Python实现HTTP服务器(二)返回指定的html页面
  10. 如何关闭hibernate产生的大量日志
  11. C#和java的语法区别
  12. ES5_03_Object扩展
  13. Microsoft强大团队(源代码)管理工具--TFS2010 与vs结合
  14. Java Web第三弹---Tomcat
  15. 工程师实战分享:77条STM32知识汇总
  16. php excel 输出条形码,excel如何将数字转换条形码
  17. Gephi 网络可视化——调整节点大小
  18. 基于51单片机的简易数字电压表proteus仿真原理图程序设计
  19. 痔疮最佳治疗方法 十人九痔 不必害羞
  20. 【Encoding】UTF-8编码规则

热门文章

  1. python3-开发进阶-RESTful 软件架构风格
  2. angular学习的一些小笔记(中)之ng-disabled轻松实现按钮是否可点击状态
  3. PhantomJS宣布终止开发
  4. CSS块元素水平垂直居中的实现技巧
  5. awk----基本用法
  6. configparser logging
  7. 程序员的幸福感和颈椎病
  8. h5启动原生APP总结
  9. 【CSS3动画】transform对文字及图片的旋转、缩放、倾斜和移动
  10. 这是我第一题AC的线段树