LeetCode刷题笔记21
剑指 Offer 36. 二叉搜索树与双向链表
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
思路
参考 https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/solution/python-xiao-bai-fen-zhi-jie-fa-by-lightchaser/
中序遍历,函数的作用是将一个节点的子树转换为双向链表
递归部分:
1、如果节点的左子树存在,则将左子树转化为双向链表,并将根节点接在返回链表的尾部(left<=root)
2、如果节点的右子树存在,则将右子树转化为双向链表,并将返回链表接在根节点的右边(root<=right)
代码
"""
# 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
"""
if root==None:
return root
def helper(root):
if root.left==None and root.right==None:
return root,root
new_head,new_end=root,root
if root.left:
head,end=helper(root.left)
end.right=root
root.left=end
new_head=head
if root.right:
head,end=helper(root.right)
root.right=head
head.left=root
new_end=end
return new_head,new_end
head,end=helper(root)
head.left=end
end.right=head
return head
面试题 04.09. 二叉搜索树序列
题目描述
从左向右遍历一个数组,通过不断将其中的元素插入树中可以逐步地生成一棵二叉搜索树。给定一个由不同节点组成的二叉搜索树,输出所有可能生成此树的数组。
示例:
给定如下二叉树
2
/ \
1 3
返回:
[
[2,1,3],
[2,3,1]
]
思路
参考:https://leetcode-cn.com/problems/bst-sequences-lcci/solution/15xing-dai-ma-by-suibianfahui/
1、使用一个queue存储下个所有可能的节点
2、然后选择其中一个作为path的下一个元素
3、递归直到queue元素为空
4、将对应的path加入结果中
5、由于二叉搜索树没有重复元素, 而且每次递归的使用元素的顺序都不一样, 所以自动做到了去重
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def BSTSequences(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return [[]]
res = []
def findPath(cur, q, path):
if cur.left:
q.append(cur.left)
if cur.right:
q.append(cur.right)
if not q:
res.append(path)
return
for i, nex in enumerate(q):
newq = q[:i] + q[i + 1:]
findPath(nex, newq, path + [nex.val])
findPath(root, [], [root.val])
return res