输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
把树分为3部分:根节点、左子树和右子树,然后把左子树中最大的节点、根节点、右子树中最小的节点链接起来。至于如何把左子树和右子树内部的节点链接成链表,那和原来的问题的实质是一样的,可以递归解决。
class Solution:
def convert_binary_search_tree(self, root):
if not root:
return root
if not root.left and not root.right:
return root
self.convert_binary_search_tree(root.left)
pre = root.left
if pre:
while pre.right:
pre = pre.right
root.left, pre.right = pre, root
self.convert_binary_search_tree(root.right)
back = root.right
if back:
while back.left:
back = back.left
root.right, back.left = back, root
while root.left:
root = root.left
return root
st = Solution()
bt = TreeNode(10)
bt.left = TreeNode(6)
bt.right = TreeNode(14)
bt.left.left = TreeNode(4)
bt.left.right = TreeNode(8)
bt.right.left = TreeNode(12)
bt.right.right = TreeNode(16)
head = st.convert_binary_search_tree(bt)
while head:
print(head.val)
head = head.right
(最近更新:2019年07月24日)
本文介绍了一种算法,将二叉搜索树转换为排序的双向链表。通过递归处理左子树和右子树,链接最大和最小节点,实现树到链表的转换。
4690

被折叠的 条评论
为什么被折叠?



