如何将二叉树就地转换为二叉搜索树,即我们不能使用任何额外的空间

发布于 2024-08-27 07:47:10 字数 39 浏览 6 评论 0原文

如何将二叉树就地转换为二叉搜索树,即我们不能使用任何额外的空间。

How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

东京女 2024-09-03 07:47:10

将二叉树转换为双向链表 - 可以在 O(n) 内完成
然后使用归并排序,nlogn
将列表转换回树 - O(n)

简单的 nlogn 解决方案。

Convert Binary Tree to a doubly linked list- can be done inplace in O(n)
Then sort it using merge sort, nlogn
Convert the list back to a tree - O(n)

Simple nlogn solution.

各自安好 2024-09-03 07:47:10

您不需要提供太多信息,但如果需求符合我的想法,那么您已经创建了一个二叉树并位于内存中,但未排序(无论如何,您希望它的排序方式)。

我假设树节点看起来像

struct tree_node {
    struct tree_node * left;
    struct tree_node * right;
    data_t data;
};

我也假设你可以阅读 C

虽然我们可以只是坐着想知道为什么这棵树是在没有按排序顺序创建的情况下创建的,这对我们没有任何好处,所以我会忽略它并对其进行排序。

不使用额外空间的要求很奇怪。暂时会有额外的空间,如果只是在堆栈上的话。我假设这意味着调用 malloc 或类似的东西,并且结果树必须使用不比原始未排序树更多的内存。

第一个也是最简单的解决方案是对未排序的树进行预序遍历,从该树中删除每个节点,然后将排序插入到新树中。这是 O(n+nlog(n)),即 O(nlog(n))。

如果这不是他们想要的,而你将不得不使用轮换和其他东西……那太可怕了!

我认为你可以通过执行奇怪版本的堆排序来做到这一点,但我遇到了问题。
我想到的另一件事是在树上进行奇怪版本的冒泡排序,这会非常慢。

为此,每个节点都会反复进行比较,并可能与其每个直接子节点(因此也与其父节点)交换,直到遍历树并且找不到任何节点
需要交换。进行摇床排序(从左到右和从右到左的冒泡排序)版本效果最好,并且在初始遍历之后,您不需要遍历相对于其父级看起来没有乱序的子树。

我确信这个算法要么是我之前的其他人想出来的,并且有一个我不知道的很酷的名字,要么它在某些方面存在我没有看到的根本缺陷。

提出第二个建议的运行时计算相当复杂。起初我认为它只是 O(n^2),就像冒泡排序和摇床排序一样,但我不能满足自己,子树遍历避免可能不足以使其比 O(n^ 2)。本质上,冒泡排序和振动排序也得到了这种优化,但只有在总排序较早发生并且您可以减少限制的末端。通过这个树版本,您也有机会避免在集合中间出现块。嗯,就像我说的,它可能有致命的缺陷。

You don't give much to go on, but if the requirement is what I think it is, you have a binary tree already created and sitting in memory, but not sorted (the way you want it to be sorted, anyway).

I'm assuming that the tree nodes look like

struct tree_node {
    struct tree_node * left;
    struct tree_node * right;
    data_t data;
};

I'm also assuming that you can read C

While we could just sit around wondering why this tree was ever created without having been created in sorted order that doesn't do us any good, so I'll ignore it and just deal with sorting it.

The requirement that no extra space be used is odd. Temporarily there will be extra space, if only on the stack. I'm going to assume that it means that calling malloc or something like that and also that the resulting tree has to use no more memory than the original unsorted tree.

The first and easiest solution is to do a preorder traversal of the unsorted tree removing each node from that tree and doing a sorted insertion into a new tree. This is O(n+nlog(n)), which is O(nlog(n)).

If this isn't what they want and you're going to have to use rotations and stuff..... that's horrible!

I thought that you could do this by doing an odd version of a heap sort, but I ran into problems.
Another thing that did come to mind, which would be horribly slow, would to do an odd version of bubble sort on the tree.

For this each node is compared and possibly swapped with each of it's direct children (and therefore also with its parent) repeatedly until you traverse the tree and don't find any
needed swaps. Doing a shaker sort (bubble sort that goes left to right and the right to left) version of this would work best, and after the initial pass you would not need to traverse down subtrees that did not look out of order with respect to it's parent.

I'm sure that either this algorthm was thought up by someone else before me and has a cool name that I just don't know, or that it is fundamentally flawed in some way that I'm not seeing.

Coming up with the run-time calculations for the second suggestion is a pretty complicated. At first I thought that it would simply be O(n^2), like bubble and shaker sorts, but I can't satisfy myself that the subtree traversal avoidance might not win enough to make it a little bit better than O(n^2). Essentially bubble and shaker sorts get this optimization too, but only at the ends where total sortedness occurs early and you can chop down the limits. With this tree version you get oppurtunities to possibly avoid chunks in the middle of the set as well. Well, like I said, it's probably fatally flawed.

半夏半凉 2024-09-03 07:47:10

执行后序遍历并从中创建二叉搜索树。

struct Node * newroot = '\0';

struct Node* PostOrder(Struct Node* root)
{
      if(root != '\0')
      {
          PostOrder(root->left);
          PostOrder(root->right);
          insertBST(root, &newroot);
      }
}

insertBST(struct Node* node, struct Node** root)
{
   struct Node * temp, *temp1;
   if( root == '\0')
   {
      *root == node;
       node->left ==  '\0';
       node->right == '\0';
   }
   else
   {
       temp = *root;
       while( temp != '\0')
       {
           temp1= temp;
           if( temp->data > node->data)
               temp = temp->left;
           else
               temp = temp->right;
       }
       if(temp1->data > node->data)
       {
           temp1->left = node;
       }
       else
       {
           temp1->right = node;
       }
       node->left = node->right = '\0';
    }
}

Do the PostOrder Traversal and from that create a Binary search tree.

struct Node * newroot = '\0';

struct Node* PostOrder(Struct Node* root)
{
      if(root != '\0')
      {
          PostOrder(root->left);
          PostOrder(root->right);
          insertBST(root, &newroot);
      }
}

insertBST(struct Node* node, struct Node** root)
{
   struct Node * temp, *temp1;
   if( root == '\0')
   {
      *root == node;
       node->left ==  '\0';
       node->right == '\0';
   }
   else
   {
       temp = *root;
       while( temp != '\0')
       {
           temp1= temp;
           if( temp->data > node->data)
               temp = temp->left;
           else
               temp = temp->right;
       }
       if(temp1->data > node->data)
       {
           temp1->left = node;
       }
       else
       {
           temp1->right = node;
       }
       node->left = node->right = '\0';
    }
}
谷夏 2024-09-03 07:47:10

执行以下算法来得出解决方案。

1)不使用任何空格找到有序后继者。

Node InOrderSuccessor(Node node)
{ 
    if (node.right() != null) 
    { 
        node = node.right() 
        while (node.left() != null)  
            node = node.left() 
        return node 
    }
    else
    { 
        parent = node.getParent(); 
        while (parent != null && parent.right() == node)
       { 
            node = parent 
            parent = node.getParent() 
        } 
        return parent 
    } 
} 

2)按顺序遍历,不使用空间。

a) 找到中序遍历的第一个节点。它应该离开树的大多数子节点(如果有),或者第一个右子节点的左侧(如果有),或者右子节点本身。
b) 使用上述算法找出第一个节点的 inoder 后继者。
c) 对所有返回的后继者重复步骤 2。

使用以上2种算法,在不使用额外空间的情况下对二叉树进行中序遍历。
遍历时形成二叉搜索树。但最坏情况下复杂度为 O(N2)

Do following algorithm to reach the solution.

1) find the in order successor without using any space.

Node InOrderSuccessor(Node node)
{ 
    if (node.right() != null) 
    { 
        node = node.right() 
        while (node.left() != null)  
            node = node.left() 
        return node 
    }
    else
    { 
        parent = node.getParent(); 
        while (parent != null && parent.right() == node)
       { 
            node = parent 
            parent = node.getParent() 
        } 
        return parent 
    } 
} 

2) Do in order traversal without using space.

a) Find the first node of inorder traversal. It should left most child of the tree if it has, or left of first right child if it has, or right child itself.
b) Use above algorithm for finding out inoder successor of first node.
c) Repeat step 2 for all the returned successor.

Use above 2 algorithm and do the in order traversal on binary tree without using extra space.
Form the binary search tree when doing traversal. But complexity is O(N2) worst case.

不可一世的女人 2024-09-03 07:47:10

好吧,如果这是一个面试问题,我脱口而出的第一件事(实际想法为零)是:递归地迭代整个二进制文件并找到最小的元素。将其从二叉树中取出。现在,重复迭代整个树并找到最小元素的过程,并将其添加为找到的最后一个元素的父元素(前一个元素成为新节点的左子元素)。根据需要重复多次,直到原始树为空。最后,你得到的是最糟糕的排序二叉树——一个链表。您的指针指向根节点,这是最大的元素。

这是一个可怕的算法 - O(n^2) 运行时间,具有最差的二叉树输出,但在想出更好的东西之前,这是一个不错的起点,并且具有您能够编写代码的优点在白板上大约 20 行。

Well, if this is an interview question, the first thing I'd blurt out (with zero actual thought) is this: iterate the entire binary recursively and and find the smallest element. Take it out of the binary tree. Now, repeat the process where you iterate the entire tree and find the smallest element, and add it as a parent of the last element found (with the previous element becoming the new node's left child). Repeat as many times as necessary until the original tree is empty. At the end, you are left with the worst possible sorted binary tree -- a linked list. Your pointer is pointing to the root node, which is the largest element.

This is a horrible algorithm all-around - O(n^2) running time with the worst possible binary tree output, but it's a decent starting point before coming up with something better and has the advantage of you being able to write the code for it in about 20 lines on a whiteboard.

转角预定愛 2024-09-03 07:47:10

二叉树通常是二叉搜索树,在这种情况下不需要转换。

也许您需要澄清要转换的内容的结构。你的源树不平衡吗?不是按照你要搜索的键排序的吗?你是如何到达源树的?

A binary tree usually is a binary search tree, in which case no conversion is required.

Perhaps you need to clarify the structure of what you are converting from. Is your source tree unbalanced? Is it not ordered by the key you want to search on? How did you arrive at the source tree?

↘紸啶 2024-09-03 07:47:10
#include <stdio.h>
#include <stdlib.h>

typedef int data_t;

struct tree_node {
    struct tree_node * left;
    struct tree_node * right;
    data_t data;
};

        /* a bonsai-tree for testing */
struct tree_node nodes[10] =
{{ nodes+1, nodes+2, 1}
,{ nodes+3, nodes+4, 2}
,{ nodes+5, nodes+6, 3}
,{ nodes+7, nodes+8, 4}
,{ nodes+9, NULL, 5}
,{ NULL, NULL, 6}
,{ NULL, NULL, 7}
,{ NULL, NULL, 8}
,{ NULL, NULL, 9}
        };

struct tree_node * harvest(struct tree_node **hnd)
{
struct tree_node *ret;

while (ret = *hnd) {
        if (!ret->left && !ret->right) {
                *hnd = NULL;
                return ret;
                }
        if (!ret->left ) {
                *hnd = ret->right;
                ret->right = NULL;;
                return ret;
                }
        if (!ret->right) {
                *hnd = ret->left;
                ret->left = NULL;;
                return ret;
                }
        hnd = (rand() &1) ? &ret->left : &ret->right;
        }

return NULL;
}

void insert(struct tree_node **hnd, struct tree_node *this)
{
struct tree_node *ret;

while ((ret= *hnd)) {
        hnd = (this->data  < ret->data ) ? &ret->left : &ret->right;
        }
*hnd = this;
}

void show(struct tree_node *ptr, int indent)
{
if (!ptr) { printf("Null\n"); return; }

printf("Node(%d):\n", ptr->data);
printf("%*c=", indent, 'L');  show (ptr->left, indent+2);
printf("%*c=", indent, 'R');  show (ptr->right, indent+2);
}

int main(void)
{
struct tree_node *root, *this, *new=NULL;

for (root = &nodes[0]; this = harvest (&root);  ) {
        insert (&new, this);
        }

show (new, 0);
return 0;
}
#include <stdio.h>
#include <stdlib.h>

typedef int data_t;

struct tree_node {
    struct tree_node * left;
    struct tree_node * right;
    data_t data;
};

        /* a bonsai-tree for testing */
struct tree_node nodes[10] =
{{ nodes+1, nodes+2, 1}
,{ nodes+3, nodes+4, 2}
,{ nodes+5, nodes+6, 3}
,{ nodes+7, nodes+8, 4}
,{ nodes+9, NULL, 5}
,{ NULL, NULL, 6}
,{ NULL, NULL, 7}
,{ NULL, NULL, 8}
,{ NULL, NULL, 9}
        };

struct tree_node * harvest(struct tree_node **hnd)
{
struct tree_node *ret;

while (ret = *hnd) {
        if (!ret->left && !ret->right) {
                *hnd = NULL;
                return ret;
                }
        if (!ret->left ) {
                *hnd = ret->right;
                ret->right = NULL;;
                return ret;
                }
        if (!ret->right) {
                *hnd = ret->left;
                ret->left = NULL;;
                return ret;
                }
        hnd = (rand() &1) ? &ret->left : &ret->right;
        }

return NULL;
}

void insert(struct tree_node **hnd, struct tree_node *this)
{
struct tree_node *ret;

while ((ret= *hnd)) {
        hnd = (this->data  < ret->data ) ? &ret->left : &ret->right;
        }
*hnd = this;
}

void show(struct tree_node *ptr, int indent)
{
if (!ptr) { printf("Null\n"); return; }

printf("Node(%d):\n", ptr->data);
printf("%*c=", indent, 'L');  show (ptr->left, indent+2);
printf("%*c=", indent, 'R');  show (ptr->right, indent+2);
}

int main(void)
{
struct tree_node *root, *this, *new=NULL;

for (root = &nodes[0]; this = harvest (&root);  ) {
        insert (&new, this);
        }

show (new, 0);
return 0;
}
廻憶裏菂餘溫 2024-09-03 07:47:10
struct Node
{
    int value;
    Node* left;
    Node* right;
};

void swap(int& l, int& r)
{
    int t = l;
    l = r;
    r = t;
}

void ConvertToBST(Node* n, Node** max)
{
    if (!n) return;

    // leaf node
    if (!n->left && !n->right)
    {
        *max = n;
        return;
    }

    Node *lmax = NULL, *rmax = NULL;
    ConvertToBST(n->left, &lmax);
    ConvertToBST(n->right, &rmax);

    bool swapped = false;
    if (lmax && n->value < lmax->value)
    {
        swap(n->value, lmax->value);
        swapped = true;
    }

    if (rmax && n->value > rmax->value)
    {
        swap(n->value, n->right->value);
        swapped = true;
    }

    *max = n;
    if (rmax && rmax->value > n->value) *max = rmax;

    // If either the left subtree or the right subtree has changed, convert the tree to BST again
    if (swapped) ConvertToBST(n, max);
}
struct Node
{
    int value;
    Node* left;
    Node* right;
};

void swap(int& l, int& r)
{
    int t = l;
    l = r;
    r = t;
}

void ConvertToBST(Node* n, Node** max)
{
    if (!n) return;

    // leaf node
    if (!n->left && !n->right)
    {
        *max = n;
        return;
    }

    Node *lmax = NULL, *rmax = NULL;
    ConvertToBST(n->left, &lmax);
    ConvertToBST(n->right, &rmax);

    bool swapped = false;
    if (lmax && n->value < lmax->value)
    {
        swap(n->value, lmax->value);
        swapped = true;
    }

    if (rmax && n->value > rmax->value)
    {
        swap(n->value, n->right->value);
        swapped = true;
    }

    *max = n;
    if (rmax && rmax->value > n->value) *max = rmax;

    // If either the left subtree or the right subtree has changed, convert the tree to BST again
    if (swapped) ConvertToBST(n, max);
}
向地狱狂奔 2024-09-03 07:47:10
***I am giving this solution in Java***

import javafx.util.Pair;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class MinimumSwapRequiredBTintoBST {
    //Node of binary tree
    public static class Node{
        int data;
        Node left;
        Node right;
        public Node(int data){
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }
    public static void main(String []arg){
        root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        System.out.print("Tree traverasl i.e inorder traversal :");
        inorder(root);
        System.out.println(" ");
        MinimumSwapRequiredBTintoBST bst = new MinimumSwapRequiredBTintoBST();
        bst.convertBTBST(root);
    }

    private static void inorder(Node root) {
        if(root == null) return;
        inorder(root.left);
        System.out.print(root.data + "  ");
        inorder(root.right);

    }

   static Node root;
    int[] treeArray;
    int index = 0;

// convert binary tree to binary search tree
    public void convertBTBST(Node node){
        int treeSize = elementsOfTree(node);
        treeArray = new int[treeSize];
        convertBtToArray(node);
        // Sort Array ,Count number of swap

        int minSwap = minimumswap(treeArray);
        System.out.println("Minmum swap required to form BT to BST :" +minSwap);
    }

    private static int minimumswap(int[] arr) {
        int n =arr.length;
        // Create two arrays and use as pairs where first
        // is element and secount array as position of first element
        ArrayList<Pair<Integer, Integer>> arrpos =
            new ArrayList<Pair<Integer, Integer>>();
        // Assign the value
        for(int i =0;i<n;i++)
        {
            arrpos.add(new Pair<Integer, Integer>(arr[i],i));
        }
// Sort the array by array element values to get right
//position of every element as the elements of secound array

        arrpos.sort(new Comparator<Pair<Integer, Integer>>() {
            @Override
            public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
                return o1.getKey()-o2.getKey();
            }
        });
// To keep track of visited elements .Initially all elements as not visited so put them as false
        int ans = 0;
        boolean []visited = new boolean[n];
        Arrays.fill(visited, false);
        // Traverse array elements
        for(int i =0;i<n;i++){
            // Already swapped and corrected or already present at correct pos
            if(visited[i] || arrpos.get(i).getValue() == i)
                continue;
            // Find out the number of nodes in this cycle and add in ans
            int cycle_size = 0;
            int j =i;
            while(!visited[j]){
                visited[j] = true;
                j = arrpos.get(j).getValue();
                cycle_size++;
            }
            if(cycle_size>0){
                ans += cycle_size-1;
            }
        }
        return ans;
    }

    private void convertBtToArray(Node node) {
        // Check whether tree is empty or not.
        if (root == null) {
            System.out.println("Tree is empty:");
            return;
        }
    else{
        if(node.left != null) {
         convertBtToArray(node.left);}
            treeArray[index] = node.data;
            index++;
            if(node.right != null){
                convertBtToArray(node.right);
            }

        }
    }
    private int elementsOfTree(Node node) {
        int height = 0;
        if(node == null) return 0;
        else{
            height = elementsOfTree(node.left )+ elementsOfTree(node.right)+1;
        }
        return height;
    }


}
***I am giving this solution in Java***

import javafx.util.Pair;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class MinimumSwapRequiredBTintoBST {
    //Node of binary tree
    public static class Node{
        int data;
        Node left;
        Node right;
        public Node(int data){
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }
    public static void main(String []arg){
        root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        System.out.print("Tree traverasl i.e inorder traversal :");
        inorder(root);
        System.out.println(" ");
        MinimumSwapRequiredBTintoBST bst = new MinimumSwapRequiredBTintoBST();
        bst.convertBTBST(root);
    }

    private static void inorder(Node root) {
        if(root == null) return;
        inorder(root.left);
        System.out.print(root.data + "  ");
        inorder(root.right);

    }

   static Node root;
    int[] treeArray;
    int index = 0;

// convert binary tree to binary search tree
    public void convertBTBST(Node node){
        int treeSize = elementsOfTree(node);
        treeArray = new int[treeSize];
        convertBtToArray(node);
        // Sort Array ,Count number of swap

        int minSwap = minimumswap(treeArray);
        System.out.println("Minmum swap required to form BT to BST :" +minSwap);
    }

    private static int minimumswap(int[] arr) {
        int n =arr.length;
        // Create two arrays and use as pairs where first
        // is element and secount array as position of first element
        ArrayList<Pair<Integer, Integer>> arrpos =
            new ArrayList<Pair<Integer, Integer>>();
        // Assign the value
        for(int i =0;i<n;i++)
        {
            arrpos.add(new Pair<Integer, Integer>(arr[i],i));
        }
// Sort the array by array element values to get right
//position of every element as the elements of secound array

        arrpos.sort(new Comparator<Pair<Integer, Integer>>() {
            @Override
            public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
                return o1.getKey()-o2.getKey();
            }
        });
// To keep track of visited elements .Initially all elements as not visited so put them as false
        int ans = 0;
        boolean []visited = new boolean[n];
        Arrays.fill(visited, false);
        // Traverse array elements
        for(int i =0;i<n;i++){
            // Already swapped and corrected or already present at correct pos
            if(visited[i] || arrpos.get(i).getValue() == i)
                continue;
            // Find out the number of nodes in this cycle and add in ans
            int cycle_size = 0;
            int j =i;
            while(!visited[j]){
                visited[j] = true;
                j = arrpos.get(j).getValue();
                cycle_size++;
            }
            if(cycle_size>0){
                ans += cycle_size-1;
            }
        }
        return ans;
    }

    private void convertBtToArray(Node node) {
        // Check whether tree is empty or not.
        if (root == null) {
            System.out.println("Tree is empty:");
            return;
        }
    else{
        if(node.left != null) {
         convertBtToArray(node.left);}
            treeArray[index] = node.data;
            index++;
            if(node.right != null){
                convertBtToArray(node.right);
            }

        }
    }
    private int elementsOfTree(Node node) {
        int height = 0;
        if(node == null) return 0;
        else{
            height = elementsOfTree(node.left )+ elementsOfTree(node.right)+1;
        }
        return height;
    }


}
疯狂的代价 2024-09-03 07:47:10

对二叉树进行中序遍历并存储结果。
按升序对结果进行排序
通过将排序列表的中间元素作为根来形成二叉搜索树(这可以使用二分搜索来完成)。这样我们就得到了平衡二叉搜索树。

Do inorder traversal of the binary tree and store the result.
sort the result in acending order
form the binary search tree by taking middle element of the sorted list as root( this can done using binary search). so we get balanced binary search tree.

維他命╮ 2024-09-03 07:47:10

堆排序树..nlogn 复杂性..

heap sort the tree.. nlogn complexity..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文