# -*- 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 not pRootOfTree.left and not pRootOfTree.right: return pRootOfTree # 处理左子树 left_tree = pRootOfTree.left # 递归调用的时候不接受返回,子树处理完即可,只有到了最根节点才返回 self.Convert(pRootOfTree.left) if left_tree: while left_tree.right: left_tree = left_tree.right # 将左子树最大节点连接到根节点 left_tree.right,pRootOfTree.left = pRootOfTree,left_tree # 处理右子树 right_tree = pRootOfTree.right self.Convert(pRootOfTree.right) if right_tree: while right_tree.left: right_tree = right_tree.left right_tree.left,pRootOfTree.right = pRootOfTree,right_tree while pRootOfTree.left: pRootOfTree = pRootOfTree.left return pRootOfTree