LeetCode 144. 二叉樹的前序遍歷
阿新 • • 發佈:2020-12-09
144. 二叉樹的前序遍歷
Difficulty: 中等
給你二叉樹的根節點 root
,返回它節點值的前序遍歷。
示例 1:
輸入:root = [1,null,2,3]
輸出:[1,2,3]
示例 2:
輸入:root = []
輸出:[]
示例 3:
輸入:root = [1]
輸出:[1]
示例 4:
輸入:root = [1,2]
輸出:[1,2]
示例 5:
輸入:root = [1,null,2]
輸出:[1,2]
提示:
- 樹中節點數目在範圍
[0, 100]
內 -100 <= Node.val <= 100
進階:遞迴演算法很簡單,你可以通過迭代演算法完成嗎?
Solution
Language: ****
迭代思路
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] stack, res = [root], [] while stack: node = stack.pop() if node: res.append(node.val) stack.append(node.right) stack.append(node.left) return res