Answers for "inorder traversal in bst"

0

bst traversal

//The following code contains all the DFS traversal 
//I have first created a Binary search tree 
//Then performed DFS search :- 1.Inorder;2.Preorder;3.Postorder
#include <iostream>

using namespace std;
struct node
{
    int data;
    node* left;
    node*right;
};
node* getnode(int value)
{
    node* temp=new node;
    temp->data=value;
    temp->left=NULL;
    temp->right=NULL;
    return temp;
}
node* insert_bst(node* roots,int value)
{
    if(roots==NULL)
    {
       return getnode(value);
    }
    if(roots->data>value)
    {
        roots->left=insert_bst(roots->left,value);
    }
    else if(roots->data<value)
    {
        roots->right=insert_bst(roots->right,value);
    }
    return roots;
}
void Inorder(node* roots)
{
    if(roots==NULL)
    {
       return;
    }
    else
    {
        Inorder(roots->left);
        cout<<roots->data<<" ";
        Inorder(roots->right);
    }
}
void post_order(node* roots)
{
    if(roots==NULL)
    {
        return;
    }
    else
    {
        post_order(roots->left);
        post_order(roots->right);
        cout<<roots->data<<" ";
    }
}
void preorder(node* root)
{
    if(root==NULL)
        return;
    cout<<root->data<<" ";
    preorder(root->left);
    preorder(root->right);
}
int main()
{
    node* root=new node;
    root=NULL;
    int number_of_nodes;
    cin>>number_of_nodes;
    int value;
    for(int i=0;i<number_of_nodes;i++)
    {
        cin>>value;
        root=insert_bst(root,value);
    }
    cout<<"Inorder Travesral:"<<endl;
    Inorder(root);
    cout<<endl;
    cout<<"Postorder traversal:"<<endl;
    post_order(root);
    cout<<endl;
    cout<<"preorder traversal:"<<endl;
    preorder(root);
    cout<<endl;
    return 0;
}
Posted by: Guest on July-26-2021
0

inorder traversal

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        return dfs(root, list);
    }
    private List<Integer> dfs(TreeNode root, List<Integer> list)
    {
        if(root == null)
            return list;
        list = dfs(root.left, list);
        list.add(root.val);
        return dfs(root.right,list);
    }
}
Posted by: Guest on July-20-2021

Browse Popular Code Answers by Language