Given a binary tree, return the preorder traversal of its nodes' values.
二叉树前序遍历(中左右)
For example:
Given binary tree{1,#,2,3},
1
\
2
/
3
return[1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
val = $val;
}
}
function preOrder($headNode) {
$arrNode[] = $headNode;
while (count($arrNode) > 0) {
$node = array_pop($arrNode);
print $node->val."\n";
if ($node->right !== null) {
$arrNode[] = $node->right;
}
if ($node->left !== null) {
$arrNode[] = $node->left;
}
}
}
$node1 = new TreeNode(1);
$node2 = new TreeNode(2);
$node3 = new TreeNode(3);
$node4 = new TreeNode(4);
$node5 = new TreeNode(5);
$node6 = new TreeNode(6);
$node1->left = $node2;
$node1->right = $node3;
$node2->right = $node4;
$node3->left = $node5;
$node3->right = $node6;
preOrder($node1);