js怎么取到遍历中的特定值_LeetCode 1028 hard 从先序遍历还原二叉树 Python解题记录...
生活随笔
收集整理的這篇文章主要介紹了
js怎么取到遍历中的特定值_LeetCode 1028 hard 从先序遍历还原二叉树 Python解题记录...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們在該專欄中記錄了我倆的刷題記錄。
我們更新的所有題目都在目錄中。
今天的題目是
力扣?leetcode-cn.com題目
We run a preorder depth first search on the root of a binary tree.At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node. (If the depth of a node is D, the depth of its immediate child is D+1. The depth of the root node is 0.)If a node has only one child, that child is guaranteed to be the left child.Given the output S of this traversal, recover the tree and return its root.我們從二叉樹的根節點 root 開始進行深度優先搜索。在遍歷中的每個節點處,我們輸出 D 條短劃線(其中 D 是該節點的深度),然后輸出該節點的值。(如果節點的深度為 D,則其直接子節點的深度為 D + 1。根節點的深度為 0)。如果節點只有一個子節點,那么保證該子節點為左子節點。給出遍歷輸出 S,還原樹并返回其根節點 root。Example 1Input: "1-2--3--4-5--6--7"Output: [1,2,5,3,4,6,7]Example 2:Input: "1-2--3---4-5--6---7"Output: [1,2,5,3,null,6,null,4,null,7]Example 3:Input: "1-401--349---90--88"Output: [1,401,null,349,88,90]思路 - DFS先序遍歷
這道題給的是先序遍歷的序列,那我們照著先序遍歷,使用一個輔助棧,把樹還原即可
在先序遍歷的過程中,如果不斷往下走,就不斷入棧,如果是往上走,就是出棧
注意,題目條件中說了,如果結點只有一個子節點,保證該子節點是左子節點。那么我們可以在建樹的時候,直接判斷當前結點的左子結點是否存在,不存在就加入到左子節點,存在就加入到右子節點
我們舉個例子直觀的說明一下
所以整個過程中,我們需要維護一個棧,同時需要寫兩個輔助函數去找當前的結點值是多少,以及當前的結點深度是多少
我們來看代碼
總結
以上是生活随笔為你收集整理的js怎么取到遍历中的特定值_LeetCode 1028 hard 从先序遍历还原二叉树 Python解题记录...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python降级pip_1.2 pip降
- 下一篇: 明日之后怎么跳过实名认证_明日之后新手教