当前位置:网站首页>剑指 Offer 36. 二叉搜索树与双向链表
剑指 Offer 36. 二叉搜索树与双向链表
2022-07-25 05:41:00 【愈努力俞幸运】
中序遍历 为对二叉树作 “左、根、右” 顺序遍历,递归实现如下:
# 打印中序遍历
def dfs(root):
if not root: return
dfs(root.left) # 左
print(root.val) # 根
dfs(root.right) # 右
解题思路:
本文解法基于性质:二叉搜索树的中序遍历为 递增序列 。
将 二叉搜索树 转换成一个 “排序的循环双向链表” ,其中包含三个要素:
排序链表: 节点应从小到大排序,因此应使用 中序遍历 “从小到大”访问树的节点。
双向链表: 在构建相邻节点的引用关系时,设前驱节点 pre 和当前节点 cur ,不仅应构建 pre.right = cur ,也应构建 cur.left = pre 。
循环链表: 设链表头节点 head 和尾节点 tail ,则应构建 head.left = tail 和 tail.right = head 。

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
纠结的点就是,为什么self.pre,self.head表示节点,好像因为力扣定义了Class Node
按下面那样写也可以,不想写nonlocal,就定义成self.xxx
"""
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution:
def treeToDoublyList(self, root):
def dfs(cur):
nonlocal pre
nonlocal head
if not cur:return
dfs(cur.left)
if pre:
pre.right,cur.left=cur,pre
if pre.val==float("inf"):head=cur
pre=cur
dfs(cur.right)
if not root: return
#self.pre = None
pre=Node(float("inf"))
head=Node(None)
dfs(root)
head.left,pre.right=pre,head
return head
边栏推荐
- CCID released the "Lake warehouse integrated technology research report", and Jushan database was selected as a typical representative of domestic enterprises
- Obj file format and.Mtl file format
- Arm PWN basic tutorial
- 微服务 - Hystrix 熔断器
- An SQL execution process
- Basset: learning the regulatory code of the accessible genome with deep convolutional neural network
- Unity accesses chartandgraph chart plug-in
- Zhanrui's first 5g baseband chip was officially released and successfully ranked among the first tier of 5g!
- Working principle and precautions of bubble water level gauge
- 剑指 Offer 05. 替换空格
猜你喜欢

Realsense d435i depth map optimization_ High precision mode

HTB-Beep

LeetCode第302场周赛

Leetcode 237. delete nodes in the linked list

Softing pngate series gateway: integrate PROFIBUS bus into PROFINET network

微服务及相关组件概念

An SQL execution process

Productivity tool in the new era -- flowus information flow comprehensive evaluation

Adaptation dynamics | in June, sequoiadb completed mutual certification with five products

Leetcode 204. 计数质数(太妙了)
随机推荐
Base64 (conversion between string and Base64 string)
[cloud co creation] design Huawei cloud storage architecture with the youngest cloud service hcie (Part 1)
School day (summer vacation daily question 2)
Single sign on (one sign on, available everywhere)
VPP cannot load up status interface
Zhou Chen, vice president of zhanrui market, responded to everything about 5g chip chunteng 510!
HTB-Arctic
sqlilabs less-28~less-8a
Basset: learning the regulatory code of the accessible genome with deep convolutional neural network
sqlilabs less-29
background
Oracle 用户A删除用户B名下的一张表后,用户B可以通过回收站恢复被删除的表吗?
Sword finger offer special shock edition day 9
PHP warehouse inventory management system source code WMS source code
obj文件格式与.mtl文件格式
Samsung folding screen has sent samples to apple and Google, and the annual production capacity will be expanded from 2.4 million to 10million!
R language data The table package performs aggregation transforms of data packets and calculates the grouping interquartile range (IQR) of dataframe data
ABC 261.D - Flipping and Bonus ( DP )
传输线理论之相速、相位等的概念
Continuous maximum sum and judgement palindrome
https://leetcode.cn/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/