例如:
输入:[8, 6, 10, 5, 6, 9, 11]
思路
这是树的层次遍历。可以使用两个辅助数组模拟队列来缓存树的结构,首先判断根节点,然后是左右子树,如果存在依次压入队列,对队列中的树依次循环判断。依次从队列中取出一个元素 push 到输出的数组中。
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function PrintFromTopToBottom(root)
{
// write code here
var arr = [], data = [];
if (root != null) {
arr.push(root);
}
while (arr.length != 0) {
var node = arr.shift();
if (node.left) {
arr.push(node.left);
}
if (node.right) {
arr.push(node.right);
}
data.push(node.val);
}
return data;
}