Easy
,Tree
,DFS
,Stack
,Binary Tree
144. Binary Tree Preorder Traversal
Given the root
of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
[0, 100]
.Node.val
<= 100Follow up: Recursive solution is trivial, could you do it iteratively?
recursive
function preorderTraversal(root) {
const result = [];
if (root === null) return result;
result.push(root.val);
result.push(...preorderTraversal(root.left));
result.push(...preorderTraversal(root.right));
return result;
}
iterative
function preorderTraversal2(root) {
const result = [];
if (root === null) return result;
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
result.push(node.val);
if (node.right !== null) stack.push(node.right);
if (node.left !== null) stack.push(node.left);
}
return result;
}
Marsgoat Jan 9, 2023
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root: return root
traversal, stk = [], [root]
while stk:
node = stk.pop()
traversal.append(node.val)
if node.right:
stk.append(node.right)
if node.left:
stk.append(node.left)
return traversal
Ron Chen Jan 9, 2023