【leetcode】99. Recover Binary Search Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/86655215

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2

Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

Follow up:

  • A solution using O(n) space is pretty straight forward.
  • Could you devise a constant space solution?

题解如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    TreeNode first = null;
    TreeNode second = null;
    TreeNode prev = new TreeNode(Integer.MIN_VALUE);
    public void recoverTree(TreeNode root) {
        //找到被错误交换的两个元素
        traverse(root);
        //交换回来
        int temp = first.val;
        first.val = second.val;
        second.val = temp;
    }
    
    public void traverse(TreeNode root) {
        if(root == null) {
            return;
        }
        
        //先遍历左子树
        traverse(root.left);
        //先找到第一个被交换的元素
        if(first == null && prev.val >= root.val) {
            first = prev;
        }
        
        //找到第二个被交换的元素,由于prev经过上次遍历的考验,所以不会是错的那个
        if(first != null && prev.val >= root.val) {
            second = root;
        }
        //记录,方便后续的比较
        prev = root;
        //遍历右子树
        traverse(root.right);
    }
}

该题的题意表明只有两个结点发错了位置,所以只需找到这两个结点并交换回来即可。

猜你喜欢

转载自blog.csdn.net/ghscarecrow/article/details/86655215
今日推荐