Leetcode 108. Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced 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.

 

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

题目意思:将一个数组中的数,构建成一个二叉查找树。(二叉查找树的性质是左子树节点的值都小于父节点的值,右子树的值都大于父节点的值)
 1 #include <stdio.h>
 2 
 3 #include <vector>
 4 struct TreeNode {
 5     int val;
 6     TreeNode *left;
 7     TreeNode *right;
 8     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 9 };
10 
11 void BST_insert(TreeNode *node, TreeNode *insert_node){
12     if (insert_node->val < node->val){
13         if (node->left){
14             BST_insert(node->left, insert_node);
15         }
16         else{
17             node->left = insert_node;
18         }
19     }
20     else{
21         if (node->right){
22             BST_insert(node->right, insert_node);
23         }
24         else{
25             node->right = insert_node;
26         }
27     }
28 }
29 
30 void preorder_insert(const std::vector<int> &nums,
31                      std::vector<TreeNode *> &node_vec,
32                      int begin, int end){
33     if (begin > end){
34         return;
35     }
36     int mid = (begin + end) / 2;
37     node_vec.push_back(new TreeNode(nums[mid]));
38     preorder_insert(nums, node_vec, begin, mid - 1);
39     preorder_insert(nums, node_vec, mid + 1, end);
40 }
41 
42 class Solution {
43 public:
44     TreeNode* sortedArrayToBST(std::vector<int>& nums) {
45         if (nums.size() == 0){
46             return NULL;
47         }
48         std::vector<TreeNode *> node_vec;
49         preorder_insert(nums, node_vec, 0, nums.size() - 1);
50         for (int i = 1; i < node_vec.size(); i++){
51             BST_insert(node_vec[0], node_vec[i]);
52         }
53         return node_vec[0];
54     }
55 };
56 
57 
58 void preorder_print(TreeNode *node,int layer){
59     if (!node){
60         return;
61     }
62     for (int i = 0; i < layer; i++){
63         printf("-----");
64     }
65     printf("[%d]\n", node->val);
66     preorder_print(node->left, layer + 1);
67     preorder_print(node->right, layer + 1);
68 }
69 
70 int main(){
71     int test[] = {-10, -3, 0, 5, 9};
72     std::vector<int> nums;
73     for (int i = 0; i < 5; i++){
74         nums.push_back(test[i]);
75     }
76     Solution solve;
77     TreeNode *root = solve.sortedArrayToBST(nums);
78     preorder_print(root, 0);
79     return 0;
80 }

 

posted @ 2018-04-07 16:22  Hwangzhiyoung  阅读(159)  评论(0编辑  收藏  举报