4.3 给定一个有序整数数组,元素各不相同按升序排列,编写一个算法,创建一棵高度最小的二叉查找树。

解答

想要使构建出来的二叉树高度最小,那么对于任意结点, 它的左子树和右子树的结点数量应该相当。比如,当我们将一个数放在根结点, 那么理想情况是,我们把数组中剩下的数对半分,一半放在根结点的左子树, 另一半放在根结点的右子树。我们可以定义不同的规则来决定这些数怎样对半分, 不过最简单的方法就是取得有序数组中中间那个数,然后把小于它的放在它的左子树, 大于它的放在它的右子树。不断地递归操作即可构造这样一棵最小高度二叉树。

与leetcode类似题目:https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

C++实现代码:

#include<vector>
#include<iostream>
using namespace std; struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}; TreeNode* helper(vector<int>::iterator begin,vector<int>::iterator end)
{
TreeNode *root=NULL;
if(begin+==end)
return new TreeNode(*begin);
if(begin>=end)
return NULL;
int mid=(end-begin)/;
root=new TreeNode(*begin+mid);
root->left=helper(begin,begin+mid);
root->right=helper(begin+mid+,end);
return root;
} TreeNode* createAVL(vector<int> &vec)
{
if(vec.empty())
return NULL;
return helper(vec.begin(),vec.end());
} void inorder(TreeNode *root)
{
if(root)
{
inorder(root->left);
cout<<root->val<<" ";
inorder(root->right);
}
}
int maxDepth(TreeNode *root)
{
if(root)
{
if(root->left==NULL&&root->right==NULL)
return ;
int leftDepth=maxDepth(root->left);
int rightDepth=maxDepth(root->right);
return leftDepth>= rightDepth ?(leftDepth+):(rightDepth+);
}
return ;
}
int main()
{
vector<int> vec= {,,,,,,,,,};
TreeNode *root=createAVL(vec);
inorder(root);
cout<<endl;
cout<<maxDepth(root)<<endl;
}

最新文章

  1. 享元模式(Flyweight Pattern)
  2. Qt学习笔记 信号和槽
  3. Embedded System.
  4. (easy)LeetCode 223.Rectangle Area
  5. ZOJ-3349 Special Subsequence 线段树优化DP
  6. 手机3D游戏开发:自定义Joystick的相关设置和脚本源码
  7. jQuery 判断div是否shown
  8. dubbo源码分析一:整体分析
  9. BZOJ 1901 Zju 2112 Dynamic Rankings 与更改的树董事长
  10. 一个网卡配置多个ip配置实现,centos7系统
  11. Qt: 非阻塞时间延迟;
  12. css3 翻转
  13. mock---前端搭建模拟服务
  14. Java 8 中常用的函数式接口
  15. Linux 中的定时处理 cron服务
  16. Python文件读写及网站显示
  17. js获取表格视图所选行号的ids
  18. H3C的DHCP中继配置命令
  19. java web 复选框checked
  20. android studio - 隐藏编辑器上面的竖线

热门文章

  1. WebBrowser控件的高级定制+mshtml
  2. uva 11646 - Athletics Track
  3. MySQL 授权详解
  4. Azure Site Recovery 通过一键式流程将虚拟机故障转移至 Azure虚拟机
  5. Android 开发性能优化之SparseArray(一)
  6. 基于WebForm+EasyUI的业务管理系统形成之旅 -- 构建Web界面(Ⅴ)
  7. [转]&quot;由于这台计算机没有远程桌面客户端访问许可证,远程会话被中断&quot;的解决方案
  8. [Andrew]Grid列编辑实现
  9. shell脚本应用(4)--常用命令
  10. Drupal安装及使用问题解决列表