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降
- 下一篇: python中unique函数_正在计算