簡體   English   中英

如何在無序二叉搜索樹中獲取節點的左右子節點?

[英]How to get the left and right child of a node in an unordered binary search tree?

我遇到了這個問題:下面的方法必須返回左子節點中的值,如果不存在則返回-1。

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

現在,參數是一個 int 值,表示父節點的值。 另一個問題是......樹沒有排序,只有正的 integer 值。 所以,我可以在根中設置 0 值,在左孩子中設置 3,在右孩子中設置 1,依此類推……我不知道如何解決這個問題。 我不能出於任何目的使用像 LinkedList 或 Stack 這樣的 ADT。 二叉樹 class 有一個字段 root,類型為 Node:

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

像這樣的東西會起作用:

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;
}

您必須在left子樹中搜索right因為樹沒有排序。 每次您找到一個有效的子樹(非空)時,您就將其添加到要搜索的元素堆棧中。 當您的搜索條件滿足時,您停止搜索。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM