ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 如果找不到节点,它应该在二进制搜索树中达到什么级别

2019-06-22 12:50:49  阅读:270  来源: 互联网

标签:java binary-search-tree depth


我正试图在我的二进制搜索树中实现这个方法,它应该告诉我找到的元素的深度.

我的问题是,如果找不到元素,我的搜索应该如何返回它退出(或被放置)的树的级别.

即,如果树中不存在该节点,则应该返回应该插入树的级别.如果在树中找不到元素,而不是应该放置它的级别,我不想返回“0”.

If I searched for “7”, the method should return “3” because that is the level where the search stopped and where in theory the “7” would be added

这是我到目前为止的代码,但它一直返回1.

public int depthSearch(Node root, int key){
    int depthLevel = 0;

    if (root==null || root.data==key){
        depthLevel++;
        return depthLevel;
    }

    if (root.data > key){
        depthSearch(root.left, key);
        depthLevel++;
        return depthLevel;
    }else{
        depthSearch(root.right, key);
        depthLevel++;
        return depthLevel;
    }
}

我的第二个问题是将深度级计数器逻辑添加到我的find方法中是否有意义?

这是方法:

public boolean find(int id){
    Node current = root;
    while(current!=null){
        if(current.data==id){
            return true;
        }else if(current.data>id){
            current = current.left;
        }else{
            current = current.right;
        }
    }
    return false;
}

提前感谢您查看我的代码.我无法在SO上找到类似问题的主题.

解决方法:

My second question is would it make sense to add the depth level
counter logic to my find method?

不,如果找到此方法则返回true,否则返回false.你不能在Java中返回多个值(你可以创建一个既能容纳这两个值的对象又可以……呃……).但即使你可以 – 一种方法应该做一件事!

至于deepSearch,实施存在问题:
您不会从递归调用返回结果.

它可以很容易地修复:

public int depthSearch(Node root, int key) {

    if (root == null || root.data == key) {
        return 1;
    }    
    else if (root.data > key) {
        return 1 + depthSearch(root.left, key);
    } else {
        return 1 + depthSearch(root.right, key);
    }
}

标签:java,binary-search-tree,depth
来源: https://codeday.me/bug/20190622/1263554.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有