综上,在中序遍历中,只需要利用一个 pre 节点和当前节点比较,如果 pre 节点的值大于当前节点的值,那么就是我们要找的逆序的数字。分别用两个指针 first 和 second 保存即可。如果找到第二组逆序的数字,我们就把 second 更新为当前节点。最后把 first 和 second 两个的数字交换即可。
执行结果:通过
执行用时:132 ms, 在所有 C# 提交中击败了 72.41% 的用户
内存消耗:27.6 MB, 在所有 C# 提交中击败了 100.00% 的用户
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ publicclassSolution { publicvoidRecoverTree(TreeNode root) { inorderTraversal(root); if(first == null || second == null) return; int temp = first.val; first.val = second.val; second.val = temp; }
private TreeNode pre = null; private TreeNode first = null; private TreeNode second = null; privatevoidinorderTraversal(TreeNode root) { if (root == null) { return; } inorderTraversal(root.left);
if (pre != null && pre.val > root.val) { //第一次遇到逆序对 if (first == null) { first = pre; second = root; } else { //第二次遇到逆序对 second = root; } } else { pre = root; }
inorderTraversal(root.right); } }
Python 语言
执行结果:通过
执行用时:64 ms, 在所有 Python3 提交中击败了 93.67% 的用户
内存消耗:14 MB, 在所有 Python3 提交中击败了 5.32% 的用户
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classSolution: defrecoverTree(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ self.inorderTraversal(root) if self.first isNoneor self.second isNone: returnNone self.first.val, self.second.val = self.second.val, self.first.val