LeetCode-in-All

102. Binary Tree Level Order Traversal

Medium

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:

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:

Solution

using LeetCodeNet.Com_github_leetcode;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public IList<IList<int>> LevelOrder(TreeNode root) {
        IList<IList<int>> result = new List<IList<int>>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new Queue<TreeNode>();
        queue.Enqueue(root);
        queue.Enqueue(null);
        List<int> level = new List<int>();
        while (queue.Count > 0) {
            root = queue.Dequeue();
            while (queue.Count > 0 && root != null) {
                level.Add((int)root.val);
                if (root.left != null) {
                    queue.Enqueue(root.left);
                }
                if (root.right != null) {
                    queue.Enqueue(root.right);
                }
                root = queue.Dequeue();
            }
            result.Add(level);
            level = new List<int>();
            if (queue.Count > 0) {
                queue.Enqueue(null);
            }
        }
        return result;
    }
}