List a Tree's Values Node, Left, Right
Implement preorderValues
You are given the root of a binary tree. Return the values of all its nodes in the order you meet them when, at every node, you take the node itself first, then walk its entire left subtree, then its entire right subtree.
A recursive helper does this directly. The same order can also be produced iteratively with a stack that holds the nodes still waiting to be taken.
Example 1:
Input: root = [10,4,15,2,7,null,18]
Output: [10,4,2,7,15,18]
Example 2:
Input: root = [3,null,8,null,5]
Output: [3,8,5]
Example 3:
Input: root = []
Output: []
+ 11 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes ≤ 100 - ●
−100 ≤ node.val ≤ 100 - ●
The tree is given as its root node (null for an empty tree); each node has a val, a left child and a right child - ●
Take every node before either of its subtrees: the node itself, then its whole left subtree, then its whole right subtree. Return the values in the order taken
root =
[10, 4, 15, 2, 7, null, 18]