- 114. 二叉树展开为【单】链表(Medium)/ 897. 二叉搜索树重排为【递增顺序搜索树】(Easy)/ 783. 二叉搜索树节点最小距离(Easy)
- 将升序数组转化为平衡二叉搜索树
【题目链接】
"""
# 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:
### 1122 中序遍历(40 ms,14.7 MB)
def treeToDoublyList(self, root: 'Node') -> 'Node':
# 定义中序遍历递归函数dfs
def dfs(cur):
# 当前节点为空直接返回
if not cur: return
# 中序遍历先递归左子树
dfs(cur.left)
# 若前一节点存在(即非头节点),则确定前一节点pre 和 当前节点cur的指向关系
if self.pre:
self.pre.right, cur.left = cur, self.pre
# 若找到头节点,则头节点为当前节点cur,也即最左的叶子节点(此else语句只会执行一次)
else:
self.head = cur
# 在递归右子树之前,需保存前一节点pre为当前节点cur,以便后续确定前、后节点的指向关系
self.pre = cur
# 中序遍历最后递归右子树
dfs(cur.right)
# 若原始树为空,则直接返回
if not root: return
# 初始化前一节点pre为None(开始时前一节点pre并不存在)
self.pre = None
# 开始整棵树的中序遍历,这是为了将这颗树排序,让每一个节点以升序来排序
dfs(root)
# 中序遍历完成后,为了实现循环链表,需要连接头尾节点
self.head.left, self.pre.right = self.pre, self.head
return self.head # 最后返回头节点head
LeetCode 109. 有序链表转换为【平衡】二叉搜索树
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
def getLength(head: ListNode) -> int:
res = 0
while head:
head = head.next
res += 1
return res
# 中序遍历
def buildTree(left: int, right: int) -> TreeNode:
if left > right:
return None
mid = (left + right + 1) // 2 # 加1是因为这里是索引相加
root = TreeNode()
root.left = buildTree(left, mid - 1) # 先左
# 第一次执行这部分代码是当上面的buildTree(left, mid - 1)已经遍历到最左叶节点
# 这样就与中序遍历对应上,每遍历一个节点对应数组中的一个值,则无需单独寻找中位数
nonlocal head
root.val = head.val
head = head.next
root.right = buildTree(mid + 1, right) # 后右
return root
length = getLength(head)
return buildTree(0, length - 1)