js怎么取到遍历中的特定值_LeetCode 1028 hard 从先序遍历还原二叉树 Python解题记录...
生活随笔
收集整理的這篇文章主要介紹了
js怎么取到遍历中的特定值_LeetCode 1028 hard 从先序遍历还原二叉树 Python解题记录...
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
我們?cè)谠搶谥杏涗浟宋覀z的刷題記錄。
我們更新的所有題目都在目錄中。
今天的題目是
力扣?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.我們從二叉樹的根節(jié)點(diǎn) root 開始進(jìn)行深度優(yōu)先搜索。在遍歷中的每個(gè)節(jié)點(diǎn)處,我們輸出 D 條短劃線(其中 D 是該節(jié)點(diǎn)的深度),然后輸出該節(jié)點(diǎn)的值。(如果節(jié)點(diǎn)的深度為 D,則其直接子節(jié)點(diǎn)的深度為 D + 1。根節(jié)點(diǎn)的深度為 0)。如果節(jié)點(diǎn)只有一個(gè)子節(jié)點(diǎn),那么保證該子節(jié)點(diǎn)為左子節(jié)點(diǎn)。給出遍歷輸出 S,還原樹并返回其根節(jié)點(diǎn) 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先序遍歷
這道題給的是先序遍歷的序列,那我們照著先序遍歷,使用一個(gè)輔助棧,把樹還原即可
在先序遍歷的過(guò)程中,如果不斷往下走,就不斷入棧,如果是往上走,就是出棧
注意,題目條件中說(shuō)了,如果結(jié)點(diǎn)只有一個(gè)子節(jié)點(diǎn),保證該子節(jié)點(diǎn)是左子節(jié)點(diǎn)。那么我們可以在建樹的時(shí)候,直接判斷當(dāng)前結(jié)點(diǎn)的左子結(jié)點(diǎn)是否存在,不存在就加入到左子節(jié)點(diǎn),存在就加入到右子節(jié)點(diǎn)
我們舉個(gè)例子直觀的說(shuō)明一下
所以整個(gè)過(guò)程中,我們需要維護(hù)一個(gè)棧,同時(shí)需要寫兩個(gè)輔助函數(shù)去找當(dāng)前的結(jié)點(diǎn)值是多少,以及當(dāng)前的結(jié)點(diǎn)深度是多少
我們來(lái)看代碼
總結(jié)
以上是生活随笔為你收集整理的js怎么取到遍历中的特定值_LeetCode 1028 hard 从先序遍历还原二叉树 Python解题记录...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python降级pip_1.2 pip降
- 下一篇: 明日之后怎么跳过实名认证_明日之后新手教