题解 | #二叉搜索树与双向链表#
二叉搜索树与双向链表
https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # # @param pRootOfTree TreeNode类 # @return TreeNode类 # class Solution: def Convert(self , pRootOfTree ): # write code here if not pRootOfTree: return None arr = self.inorderTraversal(pRootOfTree) for i in range(len(arr)-1): arr[i].right = arr[i+1] arr[len(arr)-1-i].left = arr[len(arr)-2-i] return arr[0] def inorderTraversal(self, root): if not root: return [] left = self.inorderTraversal(root.left) right = self.inorderTraversal(root.right) return left + [root] + right
使用一个辅助数组解决,将二叉搜索树按照中序遍历得到排序后结果,然后依次连接每个节点即可。