Read Binary-Tree Values in Root-Left-Right Order

Quick Overview

Traverse binary-tree values in root-left-right order with an explicit stack that answers the iterative follow-up.

Read Binary-Tree Values in Root-Left-Right Order

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Return a binary tree's values in preorder: visit the root, then its left subtree, then its right subtree. Omit absent children. ```cpp vector<int> preorderTraversal(TreeNode* root); ``` The supplied `TreeNode` contains `val`, `left`, and `right`. Brackets in examples describe tree structure in level order. ### Examples ```text Input: root = [7,3,11,1,5,null,13] Output: [7,3,1,5,11,13] ``` ```text Input: root = [] Output: [] ``` ### Constraints - There are between 0 and 100 nodes. - Values lie between -100 and 100, inclusive. ### Optional follow-up Can you perform the traversal iteratively instead of recursively?

Overview: Traverse binary-tree values in root-left-right order with an explicit stack that answers the iterative follow-up.

Amazon logo
Amazon
Date not reported
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return a binary tree's values in preorder: visit the root, then its left subtree, then its right subtree. Omit absent children.

vector<int> preorderTraversal(TreeNode* root);

The supplied TreeNode contains val, left, and right. Brackets in examples describe tree structure in level order.

Examples

Input: root = [7,3,11,1,5,null,13]
Output: [7,3,1,5,11,13]
Input: root = []
Output: []

Constraints

  • There are between 0 and 100 nodes.
  • Values lie between -100 and 100, inclusive.

Optional follow-up

Can you perform the traversal iteratively instead of recursively?