LeetCode Algorithm 606. 根据二叉树创建字符串
生活随笔
收集整理的這篇文章主要介紹了
LeetCode Algorithm 606. 根据二叉树创建字符串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
606. 根據二叉樹創建字符串
Ideas
把我珍藏多年的二叉樹前序遍歷代碼模板呈上來:
def preorderTraversalLoop(node):if not node:returnstack = [node] # list 模擬 stackwhile stack:tmp = stack.pop()print(tmp.value, end=' ')if tmp.right:stack.append(tmp.right)if tmp.left:stack.append(tmp.left)這是通過列表來模擬棧進行非遞歸前序遍歷的代碼,但是這道題跟前序遍歷還有所不同,還需要輸出額外的括號。
我們來分析一下,有以下4種情況:
對于某一個節點的括號輸出情況,我們需要在節點值輸出之前打印一個"(",然后在這顆子樹輸出完之后再輸出一個")"。
也就是說,我們在第一次到達某個節點時輸出左括號和節點值,然后將節點壓入棧中,遍歷完了子樹之后,再回到這個節點時,輸出一個右括號。
為了所有節點統一處理,我們在根節點之前也要輸出一個括號,保證統一,最后再把最外層的括號去掉就可以了。
Code
Python
class Solution:def tree2str(self, root: Optional[TreeNode]) -> str:if not root:return ''stack = [root]visit, ans = set(), ""while stack:item = stack[-1]if item in visit:stack.pop()ans += ')'else:visit.add(item)ans += f"({item.val}"if item.left is None and item.right is not None:ans += "()"if item.right:stack.append(item.right)if item.left:stack.append(item.left)return ans[1:-1]總結
以上是生活随笔為你收集整理的LeetCode Algorithm 606. 根据二叉树创建字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深度探秘 从 Auto Labeler
- 下一篇: LeetCode Algorithm 1