題目
原題頁面:https://leetcode.com/problems/binary-tree-preorder-traversal/
題目型別:Tree, Stack
難度評價:Medium
類似題目:(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?
分析
非遞迴前序遍歷二叉樹。這裡是用棧,先右孩子入棧,再左孩子入棧。隱約還記得如果是層次遍歷,即需要用隊列了。二叉樹的非遞迴遍歷中,記得後序遍歷是最複雜的,需要用兩個棧,以後再複習一下後序遍歷。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-binary-tree-preorder-traversal/
