66. 有序数组构造二叉搜索树[array to binary search tree]
【本文链接】
http://www.cnblogs.com/hellogiser/p/array-to-binary-search-tree.html
【题目】
编写一个程序,把一个有序整数数组放到二叉搜索树中。
例如 4,6,8,10,12,14,16
转换为二叉搜索树为
10
/ \
6 14
/ \ / \
4 8 12 16
【分析】
按照中序遍历的方法转换到二叉搜索树中。先要确定一个根节点,然后递归创建左右子树。
【代码】
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/*
version: 1.0 author: hellogiser blog: http://www.cnblogs.com/hellogiser date: 2014/5/31 */ // binary tree node struct struct BinaryTreeNode { int value; BinaryTreeNode *left; BinaryTreeNode *right; }; // array to tree recursively BinaryTreeNode *arrayToTree(int array[], int start, int end) { if (start > end) return NULL; int mid = (start + end) / 2; BinaryTreeNode *root = new BinaryTreeNode(); root->value = array[mid]; root->left = arrayToTree(array, start, mid - 1); root->right = arrayToTree(array, mid + 1, end); return root; } // array to tree BinaryTreeNode *ArrayToTree(int array[], unsigned int n) { if (NULL == array || n<=0) return NULL; return arrayToTree(array, 0, n - 1); } |
【参考】
http://blog.csdn.net/dahai_881222/article/details/7816127
【本文链接】
http://www.cnblogs.com/hellogiser/p/array-to-binary-search-tree.html
【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态!
【推荐】AI 的力量,开发者的翅膀:欢迎使用 AI 原生开发工具 TRAE
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
· 记一次 C# 平台调用中因非托管 union 类型导致的内存访问越界
· [EF Core]聊聊“复合”属性
· 那些被推迟的 C# 14 特性及其背后的故事
· 我最喜欢的 C# 14 新特性
· 程序员究竟要不要写文章
· 我是不是很有钱?
· 遭遇疯狂 cc 攻击的一个周末
· 【EF Core】聊聊“复合”属性
· GPT‑5 重磅发布
· 美丽而脆弱的天体运动:当C#遇见宇宙混沌