Preorder Traversal

Binary Trees Theory/Traversals Easy
  • Fun Fact: Preorder traversal of a binary tree is a classic algorithm often used in practical software development
  • For instance, in areas involving hierarchical datasets, such as the DOM (Document Object Model) in web development
  • In this context, each HTML/XML tag can be seen as a node in a tree with a hierarchical structure
  • Preorder traversal is then used to traverse the entire DOM in an orderly manner, allowing developers to effectively manipulate, add, or remove elements

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