classSolution(object):defrecoverTree(self,root):""" :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""definorder(root):ifnot root:returninorder(root.left) inorder_nodes.append(root) inorder_vals.append(root.val)inorder(root.right) inorder_nodes =[] inorder_vals =[]inorder(root) inorder_vals.sort()for i inrange(len(inorder_nodes)): inorder_nodes[i].val = inorder_vals[i]
思路2(O(1) space, O(n) time):
还是那句话,面对一道 hard 难度的题目,给出如上那么 “straight forward” 的解自然交不了差。要做到follow up的要求,我们需要知道一种叫做 Morris-Traversal 算法,这种算法可以实现 O(n) time and O(1) Space 的 Binary Tree Traversing;