简体   繁体   中英

Replace NULL with -1 in all nodes of a binary search tree

Given a Binary Search Tree Instead of making the right or left or both pointers of nodes point to NULL, make them point to nodes containing data value -1.(the -1 nodes then in turn point to NULL). Can anyone provide a code snippet for the above, preferably C++.

A solution for that is to understand a BST as an array.

Suppose you have this tree, where -1 represent children that don't exist yet:

在此处输入图像描述

If we understand the children of a node i as the nodes 2i + 1 (left child) and 2i + 2 (right child), we can represent such tree as an array like this:

[5, 3, 8, 2, 4, 6, 9, 1, -1, -1, -1, -1, 7, -1, 10]

Here's an example of such implementation with the tree above:

#include <iostream>
using namespace std;

struct BST{
    int tree[40];
    BST(){for(int i = 0; i < 40; i++) tree[i] = -1;}
    
    void add(int value){
        int i = 0;
        while(i < 40 && tree[i] != -1){
            if(tree[i] <= value) i = 2 * i + 2;
            else i = 2 * i + 1; 
        }
        tree[i] = value;
    }
};

int main (){
    BST bst;
    bst.add(5); bst.add(3); bst.add(8); bst.add(2); bst.add(4); 
    bst.add(6); bst.add(9); bst.add(1); bst.add(7); bst.add(10); 
    for(int i = 0; i < 40; i++){
        if(bst.tree[i] != -1){
            cout<<bst.tree[i]<<": ["<<bst.tree[2 * i + 1]<<", "<<bst.tree[2 * i + 2]<<"]"<<endl;
        }
    }
}

OUTPUT (node i : [left child of i , right child of i ]).

5: [3, 8]
3: [2, 4]
8: [6, 9]
2: [1, -1]
4: [-1, -1]
6: [-1, 7]
9: [-1, 10]
1: [-1, -1]
7: [-1, -1]
10: [-1, -1]

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