题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def Convert(self, root): # write code here if not root: return None if not root.left and not root.right: return root left=self.Convert(root.left) p=left while left and p.right: p=p.right if left: #right,left指链表两个指针 p.right=root root.left=p right=self.Convert(root.right) if right: right.left=root root.right=right return left if left else root
整个递归的遍历的思路还是不很清楚,最后的return不知道为什么这么写。
解题思路:
1
.将左子树构造成双链表,并返回链表头节点。
2
.定位至左子树双链表最后一个节点。
3
.如果左子树链表不为空的话,将当前root追加到左子树链表。
4
.将右子树构造成双链表,并返回链表头节点。
5
.如果右子树链表不为空的话,将该链表追加到root节点之后。
6
.根据左子树链表是否为空确定返回的节点。