Description:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
代码:
#include <iostream>
#include <vector>
#include <stack>
#define Elementype int
using namespace std;
typedef struct TreeNode //树结点
{
Elementype val;
TreeNode *left;
TreeNode *right;
TreeNode(Elementype x) : val(x), left(nullptr), right(nullptr) {}
} *Tree;
Tree SortedArrayToBinarySearchTree(iter_int first, iter_int last)
{
const auto length = distance(first,last);
if (length <= 0)
return nullptr;
auto mid = first + length / 2;
Tree root = new TreeNode(*mid);
root->left = SortedArrayToBinarySearchTree(first, mid);
root->right = SortedArrayToBinarySearchTree(mid + 1, last);
return root;
}
Tree BuildTree(vector<int>& array)
{
return SortedArrayToBinarySearchTree(array.begin(), array.end());
}
//先序遍历
void preOrderTraversal(Tree root)
{
stack<Tree> sk;
Tree p = root;
if (p)
sk.push(p);
while (!sk.empty())
{
p = sk.top();
cout << p->val<<" ";
sk.pop();
if (p->right)
sk.push(p->right);
if (p->left)
sk.push(p->left);
}
}
int main()
{
Tree root = nullptr;
vector<int> array = { 1, 3, 4, 7, 11, 15, 20, 25 };
root = BuildTree(array);
preOrderTraversal(root);
cout << endl;
system("pause");
return 0;
}
测试: