https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/
""" # Definition for a Node. class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right """ class Solution(object): def treeToDoublyList(self, root): """ :type root: Node :rtype: Node """ def preorder(current): if current is None: return preorder(current.left) if self.pre is None: self.head = current else: self.pre.right = current current.left = self.pre self.pre = current preorder(current.right) if root is None: return self.pre = None preorder(root) self.head.left = self.pre self.pre.right = self.head return self.head
https://leetcode-cn.com/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 treeToDoublyList(self, root: 'Node') -> 'Node': def dfs(cur): if not cur: return dfs(cur.left) # 递归左子树 if self.pre: # 修改节点引用 self.pre.right, cur.left = cur, self.pre else: # 记录头节点 self.head = cur self.pre = cur # 保存 cur dfs(cur.right) # 递归右子树 if not root: return self.pre = None dfs(root) self.head.left, self.pre.right = self.pre, self.head return self.head 作者:jyd 链接:https://leetcode-cn.com/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/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。