今天和大家聊的问题叫做 恢复二叉搜索树,我们先来看题面:
https://leetcode-cn.com/problems/recover-binary-search-tree/
You are given the root of a binary search tree (BST), where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
题意
给你二叉搜索树的根节点 root ,该树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。
进阶:使用 O(n) 空间复杂度的解法很容易实现。你能想出一个只使用常数空间的解决方案吗?
样例
解题
这题思路和LeetCode098——验证二叉搜索树中的思路二是一致的。
对于一棵二叉搜索树而言,其中序遍历的结果是一个递增序列。我们保存原二叉搜索树中序遍历的结果。再对该结果进行排序后得到另一个序列,比较两个序列中的不同的两个值,即为需要交换的两个错误节点。
时间复杂度是O(nlogn),其中n为树中的节点个数。空间复杂度也是O(n)。
public class Solution { List<TreeNode> list; public void recoverTree(TreeNode root) { list = new ArrayList<>(); inorderTraversal(root); List<TreeNode> tempList = new ArrayList<>(list); Collections.sort(tempList, new Comparator<TreeNode>() { @Override public int compare(TreeNode treeNode1, TreeNode treeNode2) { return treeNode1.val - treeNode2.val; } }); List<Integer> wrongList = new ArrayList<>(); for(int i = 0; i < list.size(); i++){ if(list.get(i).val != tempList.get(i).val){ wrongList.add(i); } } change(list, wrongList.get(0), wrongList.get(1)); } private void inorderTraversal(TreeNode root){ if(root == null){ return; } inorderTraversal(root.left); list.add(root); inorderTraversal(root.right); } private void change(List<TreeNode> list, int i, int j){ Integer temp = list.get(i).val; list.get(i).val = list.get(j).val; list.get(j).val = temp; } }
这道题,大家还有没有更好的解法呢?欢迎评论区讨论 。
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。

