题干
不分行从上到下打印二叉树
从上到下打印二叉树到每个节点,同一层到节点按照从左到右到顺序打印。例如,输入下图到二叉树,则依次打印出8,6,10,5,7,9,11.二叉树节点到定义如下:
class TreeNode{
int val;
TreeNode left;
TreeNode right;
}
graph TD
8-->6
8-->10
6-->5
6-->7
10-->9
10-->11
解题思路
每次打印一个节点的时候,如果该节点有子节点,则把该节点的子节点放到一个队列的末尾。接下来到队列到头部取出最早进入队列到节点,重复前面到打印操作,直至队列中所有到节点都被打印处理。
代码实现
<?php
class TreeNode
{
private $val;
private $left;
private $right;
public function __set($name, $value)
{
$this->$name = $value;
}
public function __get($name)
{
return $this->$name;
}
}
function getTree()
{
$node1 = new TreeNode();
$node1->val = 8;
$node2 = new TreeNode();
$node2->val = 6;
$node3 = new TreeNode();
$node3->val = 10;
$node1->left = $node2;
$node1->right = $node3;
$node4 = new TreeNode();
$node4->val = 5;
$node5 = new TreeNode();
$node5->val = 7;
$node2->left = $node4;
$node2->right = $node5;
$node6 = new TreeNode();
$node6->val = 9;
$node7 = new TreeNode();
$node7->val = 11;
$node3->left = $node6;
$node3->right = $node7;
return $node1;
}
function printFromTopToBottom($tree)
{
if ($tree == null) {
return;
}
$queue = [];
array_push($queue, $tree);
while (!empty($queue)) {
$node = array_shift($queue);
echo $node->val.' ';
if ($node->left != null) {
array_push($queue, $node->left);
}
if ($node->right != null) {
array_push($queue, $node->right);
}
}
}
$tree = getTree();
printFromTopToBottom($tree);