Answers for "level order traversal of binary tree c++"

C++
0

binary tree level traversal

    public static void levelOrderTraversal(Node root)
    {
        // base case
        if (root == null) {
            return;
        }
 
        // create an empty queue and enqueue the root node
        Queue<Node> queue = new ArrayDeque<>();
        queue.add(root);
 
        // to store the current node
        Node curr;
 
        // loop till queue is empty
        while (!queue.isEmpty())
        {
            // process each node in the queue and enqueue their
            // non-empty left and right child
            curr = queue.poll();
 
            System.out.print(curr.key + " ");
 
            if (curr.left != null) {
                queue.add(curr.left);
            }
 
            if (curr.right != null) {
                queue.add(curr.right);
            }
        }
    }
Posted by: Guest on January-16-2022
0

level order traversal of binary tree c++

/*
node class contains:
node* left;
node* right;
int value;
*/
void levelOrder(node* root){
  node* ptr=nullptr;
  queue<node*> q;
  q.push(root);
  while(!q.empty()){
    ptr=q.front();
    cout<<ptr->value<<endl;
    if(ptr->left!=nullptr){
q.push(ptr->left);
  }
    if(ptr->right!=nullptr){
    q.push(ptr->right);
    }
    q.pop();
  }
}
Posted by: Guest on May-01-2022

Code answers related to "level order traversal of binary tree c++"

Browse Popular Code Answers by Language