Convert Sorted Array to Balanced {-1,0,1} binary tree

 #include <iostream>
#include <vector>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int xTreeNode *leftTreeNode *right) : 
                      val(x), left(left), right(right) {}
};
TreeNode *BuildTree()
{
    int d;
    cin >> d;
    if (d == -1)
        return NULL;
    TreeNode *Node = new TreeNode(d);
    cout << "enter left child of " << d << " : ";
    Node->left = BuildTree();
    cout << "enter right child of " << d << " : ";
    Node->right = BuildTree();
    return Node;
}
void print(TreeNode *root)
{
    if (root == NULL)
        return;
    cout << root->val << " ";
    print(root->left);
    print(root->right);
}
TreeNode *buildTreeFromSortedArray(vector<int&vint sint e)
{
    if (s > e)
        return NULL;
    int mid = (s + e) / 2;
    TreeNode *root = new TreeNode(v[mid]);
    root->left = buildTreeFromSortedArray(vsmid - 1);
    root->right = buildTreeFromSortedArray(vmid + 1e);
    return root;
}
int main()
{
    vector<intv{1234567};
    TreeNode *root = buildTreeFromSortedArray(v0v.size() - 1);
    cout << "The PreOrder of Tree is: ";
    print(root);
}

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree