Binary Tree Preorder Traversal
You get the root of a binary tree. Return its values in pre-order: the node first, then its left subtree, then its right subtree. Our tree: 5 with children 8 and 1; 8 has only a left child, 3; 1 has children 6 and 2 — the answer is [5, 8, 3, 1, 6, 2].
- input
root: a binary tree, written as on LeetCode: its values level by level, left to right,nullfor a missing child.- returns
- Its values in preorder: each node first, then its left subtree, then its right subtree. An empty tree gives
[]. - constraints
- 0 ≤ the number of nodes ≤ 100
- −100 ≤ Node.val ≤ 100
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
function preorderTraversal(root) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more tree traversals problems
- 94Binary Tree Inorder TraversalEasysolve
- 145Binary Tree Postorder TraversalEasysolve
- 530Minimum Absolute Difference in BSTEasysolve
- 98Validate Binary Search TreeMediumsolve
- 230Kth Smallest Element in a BSTMediumsolve
- 114Flatten Binary Tree to Linked ListMediumsolve
- 173Binary Search Tree IteratorMediumsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.