二叉搜索树与双向链表 深度搜索 遍历二叉树 双向链表
2022/4/27 23:16:29
本文主要是介绍二叉搜索树与双向链表 深度搜索 遍历二叉树 双向链表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/
""" # Definition for a Node. class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right """ class Solution(object): def treeToDoublyList(self, root): """ :type root: Node :rtype: Node """ def preorder(current): if current is None: return preorder(current.left) if self.pre is None: self.head = current else: self.pre.right = current current.left = self.pre self.pre = current preorder(current.right) if root is None: return self.pre = None preorder(root) self.head.left = self.pre self.pre.right = self.head return self.head
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/solution/mian-shi-ti-36-er-cha-sou-suo-shu-yu-shuang-xian-5/
class Solution: def treeToDoublyList(self, root: 'Node') -> 'Node': def dfs(cur): if not cur: return dfs(cur.left) # 递归左子树 if self.pre: # 修改节点引用 self.pre.right, cur.left = cur, self.pre else: # 记录头节点 self.head = cur self.pre = cur # 保存 cur dfs(cur.right) # 递归右子树 if not root: return self.pre = None dfs(root) self.head.left, self.pre.right = self.pre, self.head return self.head 作者:jyd 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/solution/mian-shi-ti-36-er-cha-sou-suo-shu-yu-shuang-xian-5/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
这篇关于二叉搜索树与双向链表 深度搜索 遍历二叉树 双向链表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南