144. Binary Tree Preorder Traversal
Leetcode
題目
Input: root = [1,null,2,3]
Output: [1,2,3]Input: root = []
Output: []Input: root = [1]
Output: [1]解答
Last updated
Input: root = [1,null,2,3]
Output: [1,2,3]Input: root = []
Output: []Input: root = [1]
Output: [1]Last updated
var preorderTraversal = function(root) {
if (root === null) return [];
const result = [];
const preOrder = (node) => {
if (node) {
result.push(node.val);
preOrder(node.left);
preOrder(node.right);
}
}
preOrder(root);
return result;
};var preorderTraversal = function(root) {
if (root === null) return [];
const result = [];
const stack = [root];
while (stack.length) {
const node = stack.pop();
result.push(node.val);
if (node.right) {
stack.push(node.right);
}
if (node.left) {
stack.push(node.left);
}
}
return result;
};