JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

Convert a binary tree to a binary search tree

Author:JIYIK Last Updated:2025/03/18 Views:

A binary tree is a non-linear data structure. It is called a binary tree because each node has at most two children. These children are called left and right children. It can also be interpreted as an undirected graph where the topmost node is called the root. A binary search tree (BST) is a type of binary tree with a special property that helps in keeping the data organized in a sorted manner.

In this article, we will discuss how to convert a binary tree to a binary search tree while maintaining the original structure of the binary tree.

Algorithm to convert a binary tree into a binary search tree

  • Create an arrarray named to store the in-order traversal of the binary tree nodes.
  • arrSort using any sorting algorithm (merge sort O(nlogn), quick sort O(n^2), insertion sort O(n^2) etc.) .
  • Traverse the tree in order again and arrstore the elements in the sorted array in a binary tree to obtain a BST.

Converting a binary tree to a BST

Binary Tree to BST Diagram

  • We 4call an in-order traversal on the root node . Recursively traverse left to reach the node 1, which is the leftmost node, and include it in our output; since it is the root node and has no left node, we backtrack to the node 2and include it in our traversal. In this way, we traverse the entire tree and store the results of the in-order traversal [1,2,3,5,4,6]in the array arras .
  • arrSort the array using any sorting algorithm to obtain [1,2,3,4,5,6].
  • We call in-order traversal again, store the sorted array arrback into the binary tree, and get our BST.

Implementation of converting binary tree to binary search tree

#include <bits/stdc++.h>
using namespace std;

class Node {
    public:
        int data;
        Node *left, *right;
        Node(int x) {
            this->data = x;
            this->left = this->right = NULL;
        }
};
vector<int>v;

void inorder(Node *root) {
    if (root != NULL)
    {
        inorder(root->left);
        cout << root->data << " ";
        inorder(root->right);
    }
}

void storetree(Node*root, int i = 0) {
    if (!root) {
        return;
    }
    storetree(root->left);
    v.push_back(root->data);
    storetree(root->right);
}

void restoretree(Node*root, int& i) {
    if (!root) {
        return;
    }
    restoretree(root->left, i);
    root->data = v[i];
    i++;
    restoretree(root->right, i);
}

void converttoBST(Node*root) {
    if (!root) {
        return;
    }
    storetree(root);
    sort(v.begin(), v.end());
    int i = 0;
    restoretree(root, i);
}

int main() {
    Node* root = new Node(3);
    root->left = new Node(1);
    root->right = new Node(7);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->left->left->right = new Node(2);
    root->right->left = new Node(6);
    root->right->right = new Node(9);
    root->right->right->left = new Node(8);
    cout << "The inorder traversal of the tree is : "; inorder(root); cout << endl;
    converttoBST(root);
    cout << "The inorder traversal of the tree is : "; inorder(root); cout << endl;
}

Complexity of the algorithm to convert a binary tree to a BST

Time Complexity

  • Average situation

We store the array in sortedand sortedstore the array back into the binary tree with an unordered traversal time complexity of O(n). However, the complexity of sorting the array is O(nlogn), so the total complexity is given as O(nlogn)+2*O(n). The time complexity is O(nlogn).

  • Best Case

The time complexity in the best case is O(n). When the given binary tree is already a BST, we do an out-of-order traversal to implement it, and no sorting operation is required.

  • Worst case scenario

The worst case time complexity is O(nlogn).

Space complexity

Due to the additional space required for the recursive calls, the space complexity of this algorithm is O(n).

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Binary Search Tree

Publish Date:2025/03/18 Views:181 Category:ALGORITHM

A binary search tree (BST) is an ordered binary tree data structure based on nodes. A node has a value and two child nodes (a binary tree has at most two child nodes) connected to each other. A node has a value and two child nodes (a binary

Binary Tree Traversal

Publish Date:2025/03/18 Views:115 Category:ALGORITHM

A binary tree is a non-linear data structure. It is called a binary tree because each node has at most two children. These children are called left and right children. It can also be interpreted as an undirected graph where the topmost node

Circular Doubly Linked List

Publish Date:2025/03/18 Views:67 Category:ALGORITHM

A circular doubly linked list is a combination of a circular linked list and a doubly linked list. Its two nodes are connected by a previous and next pointer. The next pointer of the last node points to the first node, and the previous poin

Circular Linked List

Publish Date:2025/03/18 Views:172 Category:ALGORITHM

A circular linked list is a data structure that is slightly more complex than a linked list. It is a linked list where all the nodes are connected in a loop and form a chain. The last node does not have a NULL . Instead, it stores the addre

Doubly Linked List

Publish Date:2025/03/18 Views:69 Category:ALGORITHM

Doubly linked list is a linear data structure. It is a collection of objects defined as nodes. But unlike a linked list, the node has two pointers, one is the previous pointer and the other is the next pointer. Just like the linked list nod

Linked List Merge Sort

Publish Date:2025/03/18 Views:138 Category:ALGORITHM

In this article, we will learn how to sort a linked list using merge sort algorithm. It is one of the most preferred algorithms to sort a linked list because slow pointer random access makes the performance of other algorithms worse (for ex

C++ 二叉搜索树析构函数

Publish Date:2023/08/31 Views:179 Category:C++

本文将讨论使用 C++ 中的 delete 关键字为二叉搜索树创建析构函数。C++ 二叉搜索树析构函数

C++中逐级打印二叉树中的数据

Publish Date:2023/08/27 Views:206 Category:C++

二叉树的逐层遍历称为广度优先遍历。 本教程将教您如何使用 C++ 逐级打印二叉树中的数据,并让您熟悉执行此任务的不同方法。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial