5.3.4—二叉查找树—Convert Sorted Array to Binary Sear Tree

来源:互联网 发布:mmd双人动作数据 编辑:程序博客网 时间:2024/06/08 14:33
描述
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

#include "BinaryTree.h"#include<algorithm>#include<vector>#include<stack>using namespace std;vector<int> path;//===由有序数组构建BSTBinaryTreeNode *ConSortArrayToBST(int a[], int begin, int end){if (begin > end)return NULL;if (begin == end)return CreateBinaryTreeNode(a[(begin + end) / 2]);int mid = (begin + end) / 2;BinaryTreeNode *proot = CreateBinaryTreeNode(a[mid]);ConnectTreeNodes(proot, ConSortArrayToBST(a, begin, mid-1), ConSortArrayToBST(a, mid + 1, end));return proot;}int main(){const int n = 7;int a[n] = { 1, 3, 5, 7, 9, 11, 13 };int begin = 0;int end = n - 1;BinaryTreeNode *proot = ConSortArrayToBST(a, begin, end);PrintTree(proot);//===DestroyTree(proot);}

阅读全文
0 0
原创粉丝点击