简体   繁体   中英

How to create a method in a binary tree structure to get the parent number of a node

Here in my binary tree data structure:

//Every node has value and index
class Node<T> {
    Node<T> left,right;
    int index;
    T value;
    
    Node(T value, int index){
        this.index = index;
        this.value = value;
    }
}

class Tree<T> {
    int depth;
    Node<T> root;
    
    //Create an empty binary tree
    private static Tree<Object> empty = new Tree<>();
    
    @SuppressWarnings("unchecked")
    public static <K> Tree<K> empty(){
        return (Tree<K>) Tree.empty;
    }
    
    //creating a binary tree by taking depth as input
    public static <K> Tree<K> depth(int deepest){
      if(deepest > 0) {
          Tree<K> tree =  Tree.empty();
          tree.root = new Node<>(null,0);
          tree.addLevel(tree.root, 0, deepest, 0);
          return tree;
       } 
      else {
          throw new Error();
       }
    }
    
    private void addLevel(Node<T> node, int depth, int deepest,int index){
        if (depth == deepest - 1) {
                return;
            } else {
        node.left = new Node<>(node.value,index*2+1);
        node.right = new Node<>(node.value,index*2+2);
        addLevel(node.left,depth+1,deepest, index*2+1);
        addLevel(node.right,depth+1,deepest,index*2+2);
        }
    }
    
    public void getAllElem(Node<T> node, List<HashMap<T,Integer>> list) {
        if (node == null) {
            return;
        } 
        else {
        HashMap<T, Integer> pairs = new HashMap<T, Integer>();
        getAllElem(node.left,list);
        pairs.put(node.value, node.index);
        list.add(pairs);
        getAllElem(node.right,list);        
    }}

In that case, I want to create a method getParent(int index) , when the user pass the index number to the method, it will return the value of the parent node. For example, when the inputted index = 3, it will get the value of node(index = 1). But I don't have any clue about how to do that, any advice? Thanks!

A naive algorithm would be to from the parent node check the leaf indices and return the parent value as soon as one has found the desired leaf index, namely:

T getParent(int index, Node<T> node){
     if(node == null)
        return null;
     else if(node.left != null && node.left.index == index  || node.right != null && node.right.index == index)
         return node.value;
     else{
         T value = getParent(index, node.left);
         return (value != null) ? value : getParent(index, node.right);
    }
}

This algorithm would have a time-complexity in the worst-case scenario of N , so pretty inefficient. One could, however, try to improve it to O(log2N) , if one would search only on the right or left leaf depending on the current parent index. For that one needs to find an expression that will let one knows which leaf to continue the search.

The most efficient algorithm for this problem takes O(1) . Since for a given node with index n , their leaves will be at the indices 2n + 1 and 2n + 2 , so you can make a small table and try to figure out the formula (that based on the leaf index returns the parent index):

index | parent 
0     | no parent 
1     | 0
2     | 0
3     | 1
4     | 1
5     | 2
6     | 2
7     | 3
8     | 3
9     | 4
10    | 4

Based on that table, one can infer that code-wise, one can obtain the parent index using the formula (i-1)/2 with i > 0 , and i begin the index of the leaf that one is looking for:

i = 2 -> (2-1)/2 = 0  (the value will be rounded down)
i = 3 -> (3-1)/2 = 1
i = 4 -> (4-1)/2 = 1 (the value will be rounded down)
....
i = 10 -> (10-1)/2 = 4  (the value will be rounded down)

so the code would be something as straightforward as:

int getParentIndex(int index){
    return (index == 0) ? -1 : (index - 1) / 2;
}

However, for this algorithm to work, you need to have an additional structure that stores the nodes by indices, so that you can access their values in O(1) . For instance, using an ArrayList:

private static List<Node<T>> nodes = new ArrayList<>();

When you add a node to your tree, you also added to that list. Then with the getParentIndex method you can access that index in the list, and retrieve the Node value.

This is the typical approach used on a Binary Heap .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM