Preorder Traversal

Binary Trees Theory/Traversals Easy

Given root of binary tree, return the preorder traversal of the binary tree.

Examples:

Input : root = [1, 4, null, 4 2]

Output : [1, 4, 4, 2]

Explanation :

Input : root = [1]

Output : [1]

Explanation : Only root node is present.

Input : root = [5, 1, 2, 8, null, 4, 5, null, 6]

Constraints

  • 1 <= Number of Nodes <= 100
  • -100 <= Node.val <= 100

Hints

  • A stack can be used to simulate recursion by manually maintaining the order of traversal. Since the traversal visits the root first, push the root onto the stack, process it, then push its right child before left (so the left is processed first).
  • If the tree is empty (root is None), return an empty list. If the tree is unbalanced, the traversal should still correctly process all nodes.

Company Tags

Deloitte Ernst & Young Micron Technology JPMorgan Chase Bloomberg Western Digital Ubisoft Roblox HCL Technologies Square ARM Medtronic Uber Target Boston Consulting Group Swiggy Shopify Chewy Wayfair Broadcom Mastercard Nutanix Rockstar Games Salesforce Epic Systems Google Microsoft Amazon Meta Apple Netflix Adobe