Showing posts with label Binary traversing. Show all posts
Showing posts with label Binary traversing. Show all posts

Thursday, January 26, 2017

Binary Tree Pre Order Traversing Code

PreOrder Traversing Code in BST:

=>

    public void printPreOrder(){
       
        if(root == null){
            return;
        }
       
        Stack stack = new Stack(numNodes);
       
        stack.push(root);
       
        while(! stack.isEmpty()){
           
            Node node = stack.pop();
            System.out.println(node.data);
           
            if(node.right ! = null){
                stack.push(node.right);
            }
            if(node.left != null){
                stack.push(node.left);
            }
        }
    }

Binary Tree Inorder Traversal


Code for Inorder Traversal:

=>

    public void printInOrder(){
      
        if(root == null){
            return;
        }
      
        Stack stack = new Stack(numNodes);
        Node node = root;
        while(node != null){
            stack.push(node);
            node = node.left;
        }
      
        while(! stack.isEmpty()){
          
            node = stack.pop();
            System.out.println(node.data);
            if(node.right != null){
                stack.push(node);
                node = node.left;
            }
          
        }
   }