Python3
本题利用中序遍历+深度优先搜索解决。
参考:https://leetcode.cn/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/solution/mian-shi-ti-36-er-cha-sou-suo-shu-yu-shuang-xian-5/
根据上述思路,代码如下:
class Solution:def dfs(self, cur):if not cur: return Noneself.dfs(cur.left) if not self.pre: self.head = curelse: self.pre.right = curcur.left = self.preself.pre = cur self.dfs(cur.right) def treeToDoublyList(self, root: 'Node') -> 'Node':if not root:return Noneself.pre = Noneself.dfs(root)self.head.left = self.preself.pre.right = self.headreturn self.head
时间复杂度分析
假设二叉搜索树有NNN个节点,中序遍历需要遍历所有节点,因此时间复杂度为O(N)O(N)O(N)。