【算法】N叉树层序遍历

给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。

/**
 * Definition for a Node.
 * class Node {
 *     public $val = null;
 *     public $children = null;
 *     function __construct($val = 0) {
 *         $this->val = $val;
 *         $this->children = array();
 *     }
 * }
 */

class Solution {
    /**
     * @param Node $root
     * @return integer[][]
     */
    function levelOrder($root) {
        if ($root == null) return [];

        $queue = [$root];
        $ret = [];

        while($queue) {
            $tmp = [];
            $n = count($queue);
            for ($i = 0; $i < $n; $i++) {
                $nd = array_shift($queue);
                $tmp[] = $nd->val;
                if ($nd->children) {
                    foreach ($nd->children as $c) {
                        $queue[] = $c;
                    }
                }
            }
            $ret[] = $tmp;
        }
        return $ret;
    }
}

你可能感兴趣的:(面试那些事儿,面试题集,算法,php)