Gowthaman Ravi
Gowthy's Blog

Gowthy's Blog

Breadth-first search | Binary Tree Level Order Traversal

Breadth-first search | Binary Tree Level Order Traversal

Gowthaman Ravi's photo
Gowthaman Ravi
·Jan 28, 2022·

Subscribe to my newsletter and never miss my upcoming articles

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Example 1: LEETCODE IMAGE1.jpg Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]]

Example 2: Input: root = [1] Output: [[1]]

Example 3: Input: root = [] Output: []

Constraints: The number of nodes in the tree is in the range [0, 2000]. -1000 <= Node.val <= 1000

Java Solution

 public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
 }

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        List<List<Integer>> wrapList = new LinkedList<List<Integer>>();

        if(root == null) return wrapList;

        queue.offer(root);
        while(!queue.isEmpty()){
            int levelNum = queue.size();
            List<Integer> subList = new LinkedList<Integer>();
            for(int i=0; i<levelNum; i++) {
                if(queue.peek().left != null) queue.offer(queue.peek().left);
                if(queue.peek().right != null) queue.offer(queue.peek().right);
                subList.add(queue.poll().val);
            }
            wrapList.add(subList);
        }
        return wrapList;
    }
}

C++ Solution

/**
  Definition for a binary tree node.

  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  };

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        vector<int> res1;
        queue<TreeNode*> q;
        TreeNode* t=NULL;
        if(root==NULL)
            return res;
        q.push(root);

        while(!q.empty()){
            int s = q.size();

            for( int i=0;i<s;i++){
                t=q.front();
                q.pop();
                if(t->left!=NULL)
                    q.push(t->left);
                if(t->right!=NULL)
                    q.push(t->right);            
                res1.push_back(t->val);
            }
            res.push_back(res1);
            res1.resize(0);
        }
        return res;
    }
};
 
Share this