算法 dfs —— 将二叉树 先序遍历 转为 链表
将二叉树拆成链表
中文English
将一棵二叉树按照前序遍历拆解成为一个 假链表
。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。
Example
样例 1:
输入:{1,2,5,3,4,#,6}
输出:{1,#,2,#,3,#,4,#,5,#,6}
解释:
1
/ \
2 5
/ \ \
3 4 6
1
\
2
\
3
\
4
\
5
\
6
样例 2:
输入:{1}
输出:{1}
解释:
1
1
Challenge
不使用额外的空间耗费。
Notice
不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: a TreeNode, the root of the binary tree @return: nothing """ def flatten( self , root): # write your code here if not root: return last_node = dummy = TreeNode( None ) stack = [root] while stack: node = stack.pop() last_node.right = node if node.right: stack.append(node.right) if node.left: stack.append(node.left) node.left, node.right = None , None last_node = node |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution: last_node = None """ @param root: a TreeNode, the root of the binary tree @return: nothing """ def flatten( self , root): if root is None : return if self .last_node is not None : self .last_node.left = None self .last_node.right = root self .last_node = root right = root.right self .flatten(root.left) self .flatten(right) |
后者是使用递归的解法。但是要注意变量修改的细节。
需要在遍历中记住上次遍历节点,根据上次的节点和当前节点进行比较而得到result的算法模板:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Solution(): last_node = None result = None def run( self , root): self .dfs(root) return self .result def dfs( self ): if last_node is None : last_node = root else : do_sth(last_node, root) dfs(root.left) dfs(root.right) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2018-09-29 xrat CC特征
2017-09-29 【转】dig详解
2017-09-29 dig linux下的使用
2017-09-29 DNS RR代码和含义
2017-09-29 spark 卡在spark context,运行出现spark Exception encountered while connecting to the server : javax.security.sasl.SaslException