登录
  • #刷题
  • #leetcode

Insert In Binary Search Tree我写个helper function

akdhfikbk
720
3
我写了个helper function insert这个int,然后在刷题网站上上测试发现跟被也没insert进去呢?

[mw_shl_code=java,true]public class Solution {

public TreeNode insert(TreeNode root, int key) {

if(root==null) return new TreeNode(key);

insertNode(root,key);

return root;

}

public void insertNode(TreeNode root,int key) {

TreeNode newNode= new TreeNode(key);

TreeNode cur= root;

while(cur!=null){

if(cur.key>key){

cur=cur.left;

}else{

cur=cur.right;

}

}

cur=newNode;

return;

}

}[/mw_shl_code]

这个是运行结果:

Your answer is different from expected. Expected: [[5,3,9,1,4,8,15,null,null,null,null,null,null,12,null,10]]

Your Solution: [[5,3,9,1,4,8,15,null,null,null,null,null,null,12]]

但是我光是helper function的话,就insert进去了啊

[mw_shl_code=java,true]public static void insert(TreeNode root, int target){

TreeNode newNode= new TreeNode(target);

if(root==null) return;

TreeNode cur= root;

//先找到位置

while(cur!=null){

if(cur.val>target){

cur=cur.left;

}else{

cur=cur.right;

}

}

//找到之后,cur==null之后

cur=newNode;

return;

}[/mw_shl_code]

是我上面代码return root出了问题吗?

求教
3条回复
热度排序

发表回复