Problem
Problem page: https://leetcode.com/problems/binary-tree-preorder-traversal/
Topics: Tree, Stack
Difficulty: Medium
Similar problems: (M) Binary Tree Inorder Traversal, (M) Verify Preorder Sequence in Binary Search Tree
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3},1 \ 2 / 3return
[1,2,3].Note: Recursive solution is trivial, could you do it iteratively?
Analysis
This is a non-recursive preorder traversal of a binary tree. I use a stack here. I push the right child first, then the left child. I vaguely remember that level-order traversal needs a queue. Of the non-recursive binary tree traversals, I remember postorder being the most complicated. It takes two stacks. I'll go over postorder traversal again later.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-binary-tree-preorder-traversal/
