【问题标题】:How to get the left and right child of a node in an unordered binary search tree?如何在无序二叉搜索树中获取节点的左右子节点?
【发布时间】:2020-11-27 15:50:19
【问题描述】:

我遇到了这个问题:下面的方法必须返回左子节点中的值,如果不存在则返回-1。

public int getLeftChild(int el) {...}
/* Same for the right child */

现在,参数是一个 int 值,表示父节点的值。 另一个问题是......树没有排序,只有正整数值。 所以,我可以在根中设置 0 值,在左孩子中设置 3,在右孩子中设置 1,依此类推... 我不知道如何解决这个问题。 我不能出于任何目的使用像 LinkedList 或 Stack 这样的 ADT。 二叉树类有一个字段 roo​​t,类型为 Node:

public class Node {
    private int value;
    private Node leftChild;
    private Node rightChild;
    /*Getters and Setters...*/
}

【问题讨论】:

    标签: java binary-search-tree


    【解决方案1】:

    这样的事情会起作用:

    public int getLeftChild(int el) {
        int not_found = -1;
        Stack<Node> nodes_to_search = new Stack<>();
        nodes_to_search.add(this);
    
        while(!stack.isEmpty()){
            Node root = nodes_to_search.pop();
            if(root.value == el){
                return (root.leftChild != null) ? root.leftChild.value  : not_found;
            }
            if(root.leftChild != null)   nodes_to_search.push(root.leftChild);
            if(root.rightChild != null)  nodes_to_search.push(root.rightChild);
        }
        return not_found;
    }
    

    您必须同时搜索 leftright 子树,因为树没有排序。每次您找到一个有效的子树(不为空)时,您都将其添加到要搜索的元素堆栈中。满足搜索条件时停止搜索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多