LeetCode 144 二叉樹的前序遍歷
阿新 • • 發佈:2021-01-05
技術標籤:資料結構與演算法二叉樹leetcode演算法資料結構
給你二叉樹的根節點 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
解題思路:
建立一個Stack用來存放節點,首先我們想要列印根節點的資料,此時Stack裡面的內容為空,所以我們優先將頭結點加入Stack,然後列印。
之後應該先列印左子樹,然後右子樹。所以先加入Stack的就是右子樹,然後左子樹。
Python程式碼:
# 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]: result = [] if not root: return result stack = [root] while stack: node = stack.pop() result.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return result