# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def Convert(self, pRootOfTree): # write code here if not pRootOfTree: return None if (pRootOfTree.left == None and pRootOfTree.right == None): return pRootOfTree # 1.将左子树构造成双链表,并且返回链表头节点 left = self.Convert(pRootOfTree.left) p =left # 2.定位到左子树双链表最后一个节点 while(p!=None and p.right!=None): p = p.right # 3.如果左子树构成的双向链表不为空的话,将当前的root追加到左子树链表 if left != None: p.right = pRootOfTree pRootOfTree.left = p # 4.将右边子树构造成双链表,并返回链表头节点 right = self.Convert(pRootOfTree.right) # 5.如果右子树链表不为空,将该链表追加到root节点之后 if right != None: right.left = pRootOfTree pRootOfTree.right = right # 6.根据左子树链表是否为空确定返回的节点。 while(pRootOfTree.left): pRootOfTree=pRootOfTree.left return pRootOfTree