Left View of Binary Tree (Method 1 using recursion)

#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);
}
void LeftView(TreeNode *rootint levelint &maxLevel)
{
    if (root == NULL)
        return;
    if (level > maxLevel)
    {
        cout << root->val << " ";
        maxLevel = level;
    }
    LeftView(root->leftlevel + 1maxLevel);
    LeftView(root->rightlevel + 1maxLevel);
}
int main()
{
    TreeNode *root = BuildTree();
    cout << "Preorder of tree is: ";
    print(root);
    cout << "\nThe Left view is: ";
    int max_level = -1;
    int level = 0;
    LeftView(rootlevelmax_level);
}

Comments

Post a Comment

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)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree