Binary Tree Preorder Traversal
Description
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3Output:
[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
Solution(javascript)
/*
* @lc app=leetcode id=144 lang=javascript
*
* [144] Binary Tree Preorder Traversal
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
const preorderTraversal = function (root) {
const stack = [root]
const result = []
while (stack.length > 0) {
const node = stack.pop()
if (node) {
result.push(node.val)
stack.push(node.right, node.left)
}
}
return result
}