由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 大家帮忙看看 问题在哪啊?由preorder 来建 bst,为什么后面没
相关主题
问题在哪儿啊 kth Node of BST,大家帮忙BST查找next lowest 可以达到 O(lg N)?
帮我看一下5行代码麻烦谁贴一个bug free的BST next node
请教这么一个题:BST maximum sum path问一个leetcode上Validate Binary Search Tree的问题
这最小公共父母节点有bug吗?find the k-th maximum node in a binary search tree 有疑问
发现一个很恶心的基础问题A家面经求Offer
求问一个Java问题leetcode上的sorted list to BST
Find the node with given value in binary tree in in-order讨论几道google题(附个人答案)
请问LC上一道题:Validate BST把leetcode做完了
相关话题的讨论汇总
话题: preorder话题: beg话题: buildbst话题: end话题: treenode
进入JobHunting版参与讨论
1 (共1页)
h*********o
发帖数: 230
1
进行到第三次的build的时候,beg,end应该分别 为 2,1,此时应该返回,为什么 end
是3呢。。。
看了许久了,请大家帮忙看看问题在哪儿
public static TreeNode buildBST(int[] preorder){
if(preorder.length==0)
return null;
return buildBST(preorder,0, preorder.length-1);
}
public static TreeNode buildBST(int[] preorder, int beg, int end){

if(beg>end)
return null;
//System.out.println(beg+" "+end);
TreeNode root=new TreeNode(preorder[beg]);
int index=-1;
for(int i=beg;i<=end;i++){
if(preorder[i]>root.val){
index=i;
break;
}
}
//System.out.println(index);
root.left=buildBST(preorder, beg+1, index-1);
root.right=buildBST(preorder, index, end);

return root;


}
w***o
发帖数: 109
2
只给preorder不能保证唯一的BST。
如果只是构建任意一个符合条件的BST,把
int index=-1;
改成
int index = end + 1;
就好了。
h*********o
发帖数: 230
3
是唯一确定的吧。。。
这是bst啊
为什么改成end+1 就好了呢?

【在 w***o 的大作中提到】
: 只给preorder不能保证唯一的BST。
: 如果只是构建任意一个符合条件的BST,把
: int index=-1;
: 改成
: int index = end + 1;
: 就好了。

l*******b
发帖数: 2586
4
用到整数比较了,也就是大小给定。这就是in order了

【在 w***o 的大作中提到】
: 只给preorder不能保证唯一的BST。
: 如果只是构建任意一个符合条件的BST,把
: int index=-1;
: 改成
: int index = end + 1;
: 就好了。

1 (共1页)
进入JobHunting版参与讨论
相关主题
把leetcode做完了发现一个很恶心的基础问题
问到G家题求问一个Java问题
java问题Find the node with given value in binary tree in in-order
Create Binary Tree from preorder and inorder arrays请问LC上一道题:Validate BST
问题在哪儿啊 kth Node of BST,大家帮忙BST查找next lowest 可以达到 O(lg N)?
帮我看一下5行代码麻烦谁贴一个bug free的BST next node
请教这么一个题:BST maximum sum path问一个leetcode上Validate Binary Search Tree的问题
这最小公共父母节点有bug吗?find the k-th maximum node in a binary search tree 有疑问
相关话题的讨论汇总
话题: preorder话题: beg话题: buildbst话题: end话题: treenode