【leetcode热题100】恢复二叉搜索树

给你二叉搜索树的根节点 root ,该树中的 恰好 两个节点的值被错误地交换。请在不改变其结构的情况下,恢复这棵树 

示例 1:

输入:root = [1,3,null,null,2]
输出:[3,1,null,null,2]
解释:3 不能是 1 的左孩子,因为 3 > 1 。交换 1 和 3 使二叉搜索树有效。

示例 2:

输入:root = [3,1,4,null,null,2]
输出:[2,1,4,null,null,3]
解释:2 不能在 3 的右子树中,因为 2 < 3 。交换 2 和 3 使二叉搜索树有效。

解法一 递归

和 98 题有些像。这里的思路如下:

让我们来考虑交换的位置的可能:

  1. 根节点和左子树的某个数字交换 -> 由于根节点大于左子树中的所有数,所以交换后我们只要找左子树中最大的那个数,就是所交换的那个数

  2. 根节点和右子树的某个数字交换 -> 由于根节点小于右子树中的所有数,所以交换后我们只要在右子树中最小的那个数,就是所交换的那个数

  3. 左子树和右子树的两个数字交换 -> 找左子树中最大的数,右子树中最小的数,即对应两个交换的数
  4. 左子树中的两个数字交换
  5. 右子树中的两个数字交换

思想有了,代码很好写了。

public void recoverTree2(TreeNode root) {
    if (root == null) {
        return;
    }
    //寻找左子树中最大的节点
    TreeNode maxLeft = getMaxOfBST(root.left);
    //寻找右子树中最小的节点
    TreeNode minRight = getMinOfBST(root.right);

    if (minRight != null && maxLeft != null) {
        //左边的大于根节点,右边的小于根节点,对应情况 3,左右子树中的两个数字交换
        if ( maxLeft.val > root.val && minRight.val < root.val) {
            int temp = minRight.val;
            minRight.val = maxLeft.val;
            maxLeft.val = temp;
        }
    }

    if (maxLeft != null) {
        //左边最大的大于根节点,对应情况 1,根节点和左子树的某个数做了交换
        if (maxLeft.val > root.val) {
            int temp = maxLeft.val;
            maxLeft.val = root.val;
            root.val = temp;
        }
    }

    if (minRight != null) {
        //右边最小的小于根节点,对应情况 2,根节点和右子树的某个数做了交换
        if (minRight.val < root.val) {
            int temp = minRight.val;
            minRight.val = root.val;
            root.val = temp;
        }
    }
    //对应情况 4,左子树中的两个数进行了交换
    recoverTree(root.left);
    //对应情况 5,右子树中的两个数进行了交换
    recoverTree(root.right);

}
//寻找树中最小的节点
private TreeNode getMinOfBST(TreeNode root) {
    if (root == null) {
        return null;
    }
    TreeNode minLeft = getMinOfBST(root.left);
    TreeNode minRight = getMinOfBST(root.right);
    TreeNode min = root;
    if (minLeft != null && min.val > minLeft.val) {
        min = minLeft;
    }
    if (minRight != null && min.val > minRight.val) {
        min = minRight;
    }
    return min;
}

//寻找树中最大的节点
private TreeNode getMaxOfBST(TreeNode root) {
    if (root == null) {
        return null;
    }
    TreeNode maxLeft = getMaxOfBST(root.left);
    TreeNode maxRight = getMaxOfBST(root.right);
    TreeNode max = root;
    if (maxLeft != null && max.val < maxLeft.val) {
        max = maxLeft;
    }
    if (maxRight != null && max.val < maxRight.val) {
        max = maxRight;
    }
    return max;
}

解法二

参考 这里

如果记得 98 题,我们判断是否是一个合法的二分查找树是使用到了中序遍历。原因就是二分查找树的一个性质,左孩子小于根节点,根节点小于右孩子。所以做一次中序遍历,产生的序列就是从小到大排列的有序序列。

回到这道题,题目交换了两个数字,其实就是在有序序列中交换了两个数字。而我们只需要把它还原。

交换的位置的话就是两种情况。

  • 相邻的两个数字交换

    [ 1 2 3 4 5 ] 中 2 和 3 进行交换,[ 1 3 2 4 5 ],这样的话只产生一组逆序的数字(正常情况是从小到大排序,交换后产生了从大到小),3 2。

    我们只需要遍历数组,找到后,把这一组的两个数字进行交换即可。

  • 不相邻的两个数字交换

    [ 1 2 3 4 5 ] 中 2 和 5 进行交换,[ 1 5 3 4 2 ],这样的话其实就是产生了两组逆序的数字对。5 3 和 4 2。

    所以我们只需要遍历数组,然后找到这两组逆序对,然后把第一组前一个数字和第二组后一个数字进行交换即完成了还原。

所以在中序遍历中,只需要利用一个 pre 节点和当前节点比较,如果 pre 节点的值大于当前节点的值,那么就是我们要找的逆序的数字。分别用两个指针 first 和 second 保存即可。如果找到第二组逆序的数字,我们就把 second 更新为当前节点。最后把 first 和 second 两个的数字交换即可。

中序遍历,参考 94 题 ,有三种方法,递归,栈,Morris 。这里的话,我们都改一下。

1. 递归版中序遍历

TreeNode first = null;
TreeNode second = null;
public void recoverTree(TreeNode root) {
    inorderTraversal(root);
    int temp = first.val;
    first.val = second.val;
    second.val = temp;
}
TreeNode pre = null;
private void inorderTraversal(TreeNode root) {
    if (root == null) {
        return;
    }
    inorderTraversal(root.left); 
    /*******************************************************/
    if(pre != null && root.val < pre.val) {
        //第一次遇到逆序对
        if(first==null){
            first = pre;
            second = root;
        //第二次遇到逆序对
        }else{
            second = root;
        }
    }
    pre = root; 
    /*******************************************************/
    inorderTraversal(root.right);
}

2. 栈版中序遍历

TreeNode first = null;
TreeNode second = null;

public void recoverTree(TreeNode root) {
    inorderTraversal(root);
    int temp = first.val;
    first.val = second.val;
    second.val = temp;
}

public void inorderTraversal(TreeNode root) {
    if (root == null)
        return;
    Stack<TreeNode> stack = new Stack<>();
    TreeNode pre = null;
    while (root != null || !stack.isEmpty()) {
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
        root = stack.pop();
        /*******************************************************/
        if (pre != null && root.val < pre.val) {
            if (first == null) {
                first = pre;
                second = root;
            } else {
                second = root;
            }
        }
        pre = root;
        /*******************************************************/
        root = root.right;
    }
}

3. Morris 版中序遍历

因为之前这个方法中用了 pre 变量,为了方便,这里也需要 pre 变量,我们用 pre_new 代替。具体 Morris 遍历算法参见 94 题 。利用 Morris 的话,我们的空间复杂度终于达到了 O(1)。

public void recoverTree(TreeNode root) {
    TreeNode first = null;
    TreeNode second = null;
    TreeNode cur = root;
    TreeNode pre_new = null;
    while (cur != null) {
        // 情况 1
        if (cur.left == null) {
            /*******************************************************/
            if (pre_new != null && cur.val < pre_new.val) {
                if (first == null) {
                    first = pre_new;
                    second = cur;
                } else {
                    second = cur;
                }
            }
            pre_new = cur;
            /*******************************************************/
            cur = cur.right;
        } else {
            // 找左子树最右边的节点
            TreeNode pre = cur.left;
            while (pre.right != null && pre.right != cur) {
                pre = pre.right;
            }
            // 情况 2.1
            if (pre.right == null) {
                pre.right = cur;
                cur = cur.left;
            }
            // 情况 2.2
            if (pre.right == cur) {
                pre.right = null; // 这里可以恢复为 null
                /*******************************************************/
                if (pre_new != null && cur.val < pre_new.val) {
                    if (first == null) {
                        first = pre_new;
                        second = cur;
                    } else {
                        second = cur;
                    }
                }
                pre_new = cur;
                /*******************************************************/
                cur = cur.right;
            }
        }
    }

    int temp = first.val;
    first.val = second.val;
    second.val = temp;
}
  • 16
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 5. Longest Palindromic Substring 6. ZigZag Conversion 7. Reverse Integer 8. String to Integer (atoi) 9. Palindrome Number 10. Regular Expression Matching 11. Container With Most Water 12. Integer to Roman 13. Roman to Integer 14. Longest Common Prefix 15. 3Sum 16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Swap Nodes in Pairs 24. Reverse Nodes in k-Group 25. Remove Duplicates from Sorted Array 26. Remove Element 27. Implement strStr() 28. Divide Two Integers 29. Substring with Concatenation of All Words 30. Next Permutation 31. Longest Valid Parentheses 32. Search in Rotated Sorted Array 33. Search for a Range 34. Find First and Last Position of Element in Sorted Array 35. Valid Sudoku 36. Sudoku Solver 37. Count and Say 38. Combination Sum 39. Combination Sum II 40. First Missing Positive 41. Trapping Rain Water 42. Jump Game 43. Merge Intervals 44. Insert Interval 45. Unique Paths 46. Minimum Path Sum 47. Climbing Stairs 48. Permutations 49. Permutations II 50. Rotate Image 51. Group Anagrams 52. Pow(x, n) 53. Maximum Subarray 54. Spiral Matrix 55. Jump Game II 56. Merge k Sorted Lists 57. Insertion Sort List 58. Sort List 59. Largest Rectangle in Histogram 60. Valid Number 61. Word Search 62. Minimum Window Substring 63. Unique Binary Search Trees 64. Unique Binary Search Trees II 65. Interleaving String 66. Maximum Product Subarray 67. Binary Tree Inorder Traversal 68. Binary Tree Preorder Traversal 69. Binary Tree Postorder Traversal 70. Flatten Binary Tree to Linked List 71. Construct Binary Tree from Preorder and Inorder Traversal 72. Construct Binary Tree from Inorder and Postorder Traversal 73. Binary Tree Level Order Traversal 74. Binary Tree Zigzag Level Order Traversal 75. Convert Sorted Array to Binary Search Tree 76. Convert Sorted List to Binary Search Tree 77. Recover Binary Search Tree 78. Sum Root to Leaf Numbers 79. Path Sum 80. Path Sum II 81. Binary Tree Maximum Path Sum 82. Populating Next Right Pointers in Each Node 83. Populating Next Right Pointers in Each Node II 84. Reverse Linked List 85. Reverse Linked List II 86. Partition List 87. Rotate List 88. Remove Duplicates from Sorted List 89. Remove Duplicates from Sorted List II 90. Intersection of Two Linked Lists 91. Linked List Cycle 92. Linked List Cycle II 93. Reorder List 94. Binary Tree Upside Down 95. Binary Tree Right Side View 96. Palindrome Linked List 97. Convert Binary Search Tree to Sorted Doubly Linked List 98. Lowest Common Ancestor of a Binary Tree 99. Lowest Common Ancestor of a Binary Search Tree 100. Binary Tree Level Order Traversal II

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值