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

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {
    /**
     * @param TreeNode $root
     * @return Integer[][]
     */
    function levelOrder($root) {
        $result = array();
        if ($root == null) {
            return $result;
        }
        $queue = new \SplQueue();
        $queue->enqueue($root);
        $queue->enqueue(null);
        $level = array();
        while (!$queue->isEmpty()) {
            $root = $queue->dequeue();
            while (!$queue->isEmpty() && $root != null) {
                array_push($level, $root->val);
                if ($root->left != null) {
                    $queue->enqueue($root->left);
                }
                if ($root->right != null) {
                    $queue->enqueue($root->right);
                }
                $root = $queue->dequeue();
            }
            array_push($result, $level);
            $level = array();
            if (!$queue->isEmpty()) {
                $queue->enqueue(null);
            }
        }
        return $result;
    }
}