Tree: Level Order Traversal

Sort by

recency

|

582 Discussions

|

  • + 0 comments

    void levelOrder(Node * root) { if (root == nullptr) return;

    queue<Node*> q;
    q.push(root);
    
    while (!q.empty()) {
        Node* current = q.front();
        q.pop();
    
        cout << current->data << " ";
    
        if (current->left != nullptr) {
            q.push(current->left);
        }
    
        if (current->right != nullptr) {
            q.push(current->right);
        }
    }
    

    }

  • + 0 comments
    1. if(root==NULL) return; queueq; q.push(root); while(!q.empty()){ Node*current=q.front(); q.pop(); cout<data<<" "; if(current->left!=NULL){ q.push(current->left); } if(current->right!=NULL){ q.push(current->right); } }
  • + 0 comments

    //for cpp if(root == NULL) return; queue q; q.push(root);

        while(!q.empty()){
            Node* current = q.front();
            q.pop();
            cout<<current->data<<" ";
            if(current->left!=NULL)
            q.push(current->left);
            if(current->right!=NULL)
            q.push(current->right);
    
  • + 0 comments
    void printLevel(Node* root) {
        if (!root) return; 
    
        queue<Node*> q;
        q.push(root);
    
        while (!q.empty()) {
            Node* node = q.front();
            q.pop();
    
            cout << node->data << " ";
    
            if (node->left)  q.push(node->left);
            if (node->right) q.push(node->right);
        }
    }
    
  • + 0 comments

    Here is my solutions using an arrayList and HashMap

    private static HashMap<Integer, List<Integer>> treeLevels = new HashMap<>();
        private static void addLevels(Node node, int level){
            if(node == null){
                return;
            }
            
            List<Integer> levels;
            
            if(treeLevels.containsKey(level)){
                levels = treeLevels.get(level);
            }else{
                levels = new ArrayList<>();
            }
            
            levels.add(node.data);
            treeLevels.put(level, levels);
            addLevels(node.left, level + 1);
            addLevels(node.right, level + 1);
            
        }
    	public static void levelOrder(Node root) {
          addLevels(root, 0);
          for(List<Integer> list: treeLevels.values()){
            for(int val: list){
                System.out.printf("%d ", val);
            }
          }
          
        }