Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

tree traversal

# Depth First Traversals: 
(a) Inorder (Left, Root, Right) 
(b) Preorder (Root, Left, Right)  
(c) Postorder (Left, Right, Root) 
Comment

tree traversal

const breadthFirstTraversal = (root) => {
  if (root === null) return [];

  const result = [];
  const queue = [root];

  while (queue.length > 0) {
    const current = queue.shift();
    result.push(current.data);
    if (current.left) queue.push(current.left);
    if (current.right) queue.push(current.right);
  }
  return result;
};
Comment

inorder traversal of tree

//*******this is a C program for implementation and searching in A BT*******
#include<stdlib.h>
#include <stdio.h>

struct BinaryTree{
    int data;
    struct BinaryTree*right;
    struct BinaryTree*left;
};

struct BinaryTree*createnode(int val){
    struct BinaryTree*root=(struct BinaryTree*)malloc(sizeof(struct BinaryTree));
    root->data=val;
    root->left=NULL;
    root->right=NULL;
    
}

void inorder(struct BinaryTree*root){
    if(root==NULL){
    return;
    }
    else {inorder(root->left);
    printf("%d->",root->data);
    inorder(root->right);
}

}
 
void preorder(struct BinaryTree*root){
    if(root==NULL){
        return;
    }
    else {
        printf("%d->",root->data);
        preorder(root->left);
        preorder(root->right);
    }
}

void postorder(struct BinaryTree*root){
    if(root==NULL){
        return;
    }
    else{
        postorder(root->left);
        postorder(root->right);
        printf("%d->",root->data);
    }
}
int main()
{
    printf("Lets grow the tree
");
    struct BinaryTree*root=createnode(1);
    root->left=createnode(2);
    root->right=createnode(3);
    root->left->left=createnode(4);
    root->left->right=createnode(5);
    
    printf("tree has grown up
");
    
    printf("Inorder traversal ");
    inorder(root);printf("NULL");

    printf("
preorder traversal ");
    preorder(root);printf("NULL");
    
    printf("
Postorder  traversal");
    postorder(root);printf("NULL");
    
    return 0 ;
}
Comment

Tree traversal

A tree is a graph whose degree of node== # of it's children & is acyclic 
Binary tree is a tree with each node having atmost 2 children.
2 ways to traverse each node once:
BFS - level wise
DFS - BY RECURSIVELY TRAVERSING ROOT,LEFT SUBTREE (L) & RIGHT SUBTREE (R)
NOTE: THERE ARE 3! WAYS OF DOING A DFS, BASED ON ORDER OF Root,L,R.     
but only 3 are useful :
Root,L,R- preorder traversal 
L,Root,R- inorder traversal 
L,R,Root- postorder traversal
Comment

Tree: Postorder Traversal

def postOrder(root):
    if root:
        postOrder(root.left)
        postOrder(root.right)
        print(root, end = " ")
Comment

traversal tree

class Node:
     def __init__(self,data):
          self.data = data
          self.parent = None
          self.left = None
          self.right = None

     def __repr__(self):
          return repr(self.data)

     def add_left(self,node):
         self.left = node
         if node is not None:
             node.parent = self

     def add_right(self,node):
         self.right = node
         if node is not None:
             node.parent = self
'''
Example:
          _2_
        /       
       7         9
      /          
     1   6         8
         /        / 
       5   10   3   4
'''
def create_tree():
    two = Node(2)
    seven = Node(7)
    nine = Node(9)
    two.add_left(seven)
    two.add_right(nine)
    one = Node(1)
    six = Node(6)
    seven.add_left(one)
    seven.add_right(six)
    five = Node(5)
    ten = Node(10)
    six.add_left(five)
    six.add_right(ten)
    eight = Node(8)
    three = Node(3)
    four = Node(4)
    nine.add_right(eight)
    eight.add_left(three)
    eight.add_right(four)

    # now return the root node
    return two

def pre_order(node):
    print(node)
    if node.left:
        pre_order(node.left)
    if node.right:
        pre_order(node.right)

def in_order(node):
    if node.left:
        in_order(node.left)
    print(node)
    if node.right:
        in_order(node.right)

def post_order(node):
    if node.left:
        post_order(node.left)
    if node.right:
        post_order(node.right)
    print(node)

if __name__ == "__main__":
    root = create_tree()
    print("
Pre-order traversal:")
    pre_order(root)
    print("
In-order traversal:")
    in_order(root)
    print("
Post-order traversal:")
    post_order(root)
Comment

Tree: Inorder Traversal

def inOrder(root):
    if root:
        inOrder(root.left)
        print(root, end = " ")
        inOrder(root.right)        
        
Comment

Preorder, inorder & postorder traversal code

class Node:
    def __init__(self, k):
        self.left = None
        self.right = None
        self.key = k


def inorder(root):
    if root != None:
        inorder(root.left)
        print(root.key)
        inorder(root.right)


# Driver Code

root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.right.left = Node(40)
root.right.right = Node(50)

inorder(root)

# time complexity (using recurrence tree method)  - O(n)
where, 
n == total nodes 
# space complexity - O(height of tree)
Note: height can be both n (if each node has exactly 1 child) and 
log(n) (if every node has exactly 2 children).

# IMP NOTE : FOR PREORDER AND POSTORDER JUST ORDER OF STATEMENTS CHANGE

for ex:
below is preorder & postorder traversal with same time & space complexity as inorder

def preorder(root):
    if root == None:
        return
    print(root.key)
    preorder(root.left)
    preorder(root.right)

def postorder(root):
    if root == None:
        return
    preorder(root.left)
    preorder(root.right)
    print(root.key)
    
Comment

PREVIOUS NEXT
Code Example
Python :: python coding practice 
Python :: dict comprehension python 
Python :: insert-cells-in-empty-pandas-dataframe 
Python :: python strftime cheat sheet 
Python :: python argsort 
Python :: Generate bootstrap sample 
Python :: automl classification tutorial sklearn 
Python :: percent sign in python 
Python :: python concatenate dictionaries 
Python :: dimension of an indez pandas 
Python :: float python 
Python :: save jupyter notebook session 
Python :: parse invoice python 
Python :: cv2 videowriter python not working 
Python :: scrape website with login python selenium 
Python :: how to devided array into parts python 
Python :: for in print pyhton 
Python :: how to take n space separated input in python” Code Answer’s 
Python :: convert word to pdf python 
Python :: date and time in python 
Python :: draw bipartite graph networkx 
Python :: serialize list to json python 
Python :: puython is not equal to 
Python :: seaborn orient 
Python :: how to create a 2d array in python 
Python :: str count python 
Python :: additionner liste python 
Python :: dependency injection python 
Python :: convert series to dataframe pandas 
Python :: select each two elements on a list python 
ADD CONTENT
Topic
Content
Source link
Name
8+6 =