Sorted Array to Completed BST

Problem

Given a sorted array. Write a function that creates a Balanced Binary Search Tree using array elements.

Examples

Input:  Array {1, 2, 3}
Output: A Balanced BST
     2
   /  \
  1    3 

Input: Array {1, 2, 3, 4}
Output: A Balanced BST
      3
    /  \
   2    4
 /
1

Algorithm

  1) Notice the left child is 2i + 1 and right child is 2 * i + 2 for node i, where i is the index from level ordering
  2) Recursively construct Completed BST for the left and right child
  3) As it's in order traverse, we keep cnt as the visited node count so far
struct TreeNode
{
	TreeNode(int _val, TreeNode* _left = nullptr, TreeNode* _right = nullptr): val(_val), left(_left), right(_right){}
	int val;
	TreeNode* left;
	TreeNode* right;
};
class Solution
{
	vector<int> num;
	int cnt;
	TreeNode* convert(vector<int>& _num)
	{
		cnt = 0;
		num = _num;
		return dfs(0);
	}
	TreeNode* dfs(int i)
	{
		if (i >= num.size()) return nullptr;
		TreeNode* left = dfs(2 * i + 1);
		TreeNode* root = new TreeNode(num[cnt++], left);
		root->right = dfs(2 * i + 2);
		return root;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值