Turning a Binary Tree to a sorted array

眉间皱痕 提交于 2020-06-27 11:12:34

问题


Is there a way to turn a Binary to a sorted array without having to traverse the tree for every array index?

Node root;
Node runner;
int current_smallest;

void findsmallest(Node root){
    //Pre-order traversal
    if(root == null){
        return;
    }else{
        runner = root;
        if(current_smallest == null){
            current_smallest = runner.element;
        }else{
            if(current_smallest > runner.element){
            current_smallest = runner.element;
            }
        }
        findsmallest(runner.left);
        findsmallest(runner.right);
    }   
}

void fill_array( int [] array ){

    for(int i =0; i < array.length(); i++){
        findsmallest(root);
        array[i] = current_smallest;
    }
} 

As you can see this can be take a long time if there are a lot of nodes in the tree. Btw, I forgot to show that the whole tree would have to be traversed at the start to get the length of the array.


回答1:


Yes, you can do that: run an in-order traversal of the tree, keep the current position of the array, and store the node's value at the then-current position of the array.

You can do in-order traversal recursively, or you can do it with a stack data structure. If you want to do it recursively, you can do this:

int fill_array(Node root, int [] array, int pos) {
    if (root.left != null) {
        pos = fill_array(root.left, array, pos);
    }
    array[pos++] = root.element;
    if (root.right != null) {
        pos = fill_array(root.right, array, pos);
    }
    return pos; // return the last position filled in by this invocation
}

Note that in order for the above recursive procedure to work, the caller must allocate enough space in the array passed into the function.




回答2:


A binary tree can be represented in an array; if this were the case, all you would need to do is sort the array.

Here's some more info on representing the tree in the array: wikipedia

This is not necessarily the most space-efficient representation; the "nodes with references" representation may waste less space.




回答3:


What you want is an in-order traversal, which is generally implemented recursively like:

  • Traverse left subtree.
  • Handle this node (ie. insert as the next element in your array)
  • Traverse right subtree.


来源:https://stackoverflow.com/questions/16180569/turning-a-binary-tree-to-a-sorted-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!