赞
踩
描述:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
<?php /*class TreeNode{ var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } }*/ function MyPrint($pRoot) { $q = new SplQueue(); if(!$pRoot){ return []; } $result = []; $i=0; $q->push($pRoot); while(!$q->isEmpty()){ $count = $q->count(); while($count--){ $t = $q->shift(); if($t){ $result[$i][] = $t->val; $q->push($t->left); $q->push($t->right); } } $i++; } return $result; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。