java - Recursive minimal tree creating function buggy?
问题描述
From an exercise in Cracking the Coding Interview: Given a sorted (increasing order) array with unique integer elements, write an algorithm that will create a binary search tree with minimal height.
The algorithm structure is:
Insert into the tree the middle element of array (is root).
Insert (into left subtree) the left subarray elements.
Insert (into right subtree) the right subarray elements.
Recurse.
But the actual code I believe is buggy. Given an array that holds {6, 7, 8, 9, 10}, it'll insert the 6 twice into the left subtree. This is because of int mid = (start + end) / 2; The code will never insert node 7 into the left subtree tree because it is at index 1, and the mid variable won't evaluate to 1.
Node createMinimalBST(int arr[]) {
return createMinimalBST(array, 0, array.length - 1);
}
Node createMinimalBST(int arr[], int start, int end) {
if (end < start) {
return null;
}
int mid = (start + end) / 2;
Node n = new Node(arr[mid]);
n.left = createMinimalBST(arr, start, mid - 1);
n.right = createMinimalBST(arr, mid + 1, end);
return n;
}
解决方案
There is nothing wrong with the algorithm or the code logic. Below is exactly how the binary search tree will look like after the insertions as per the code.
8
/ \
6 9
\ \
7 10
Working code of the logic :
#include <iostream>
using namespace std;
typedef struct node {
int val;
node *left, *right;
node(int value){
val = value;
left = right = NULL;
}
}Node;
Node* createMinimalBST(int arr[], int start, int end) {
if (end < start)
return NULL;
int mid = (start + end) / 2;
Node *n = new Node(arr[mid]);
n->left = createMinimalBST(arr, start, mid - 1);
n->right = createMinimalBST(arr, mid + 1, end);
return n;
}
Node* createMinimalBST(int arr[], int size) {
return createMinimalBST(arr, 0, size - 1);
}
int main() {
int a[] = {6, 7, 8, 9, 10};
Node *root = createMinimalBST(a, 5);
cout << root->val << endl;
cout << root->left->val << endl;
cout << root->right->val << endl;
cout << root->left->right->val << endl;
cout << root->right->right->val << endl;
return 0;
}
Output of the code :
8
6
9
7
10
推荐阅读
- sql - 在 Laravel 中计算两个带有时间戳的日期之间的差异
- ios - 在 SwiftUI 中加载异步请求时显示活动指示器
- python - 在 docker 容器中找不到 Python 模块
- git - git status 时不想看到很少修改的文件
- postgresql - Postgresql 函数表名参数
- c++ - 为什么我已经定义了一个未初始化的局部变量错误?
- wordpress - Wordpress - 外部开发人员添加了这些页面文件夹 - 如何将页面从一个文件夹移动到另一个文件夹?
- r - 是否可以将转换结果存储在 SQL 服务器中的变量(R 脚本/ Power Query 之类)中
- python - 我正在尝试制作一个将 iptables 添加到我的服务器的 python 脚本,但我遇到了一些错误
- c# - 抛出异常:根据验证程序,远程证书无效