99. Recover Binary Search Tree

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

Recover the tree without changing its structure.

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

一刷
题解:
我们用中序遍历,这样子如果是正常顺序应该是顺序的。
碰到第一个不满足要求的点,相邻的点左(较大)>右,那么第一个不满足要求的为左边这个点。碰到第二个不满足要求的点,左>右(较小)。因为之后要交换这两个点。那么第二个不满足要求的为右边的点。然后直接交换两个节点的val就可以。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode firstNode = null;
    TreeNode secondNode = null;
    TreeNode prev = new TreeNode(Integer.MIN_VALUE);
    
    public void recoverTree(TreeNode root) {
        //find the node
        traverse(root);
        
        //swap
        int val = firstNode.val;
        firstNode.val = secondNode.val;
        secondNode.val = val;
        
    }
    
    private void traverse(TreeNode root){
        if(root==null) return;
        traverse(root.left);
        
        
        if(firstNode==null && prev.val > root.val){
            firstNode = prev;
        }
        
        if(firstNode!=null && prev.val > root.val){
            secondNode = root;
        }
        
        prev = root;
        
        traverse(root.right);
    }
}

二刷
思路同一刷

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode first = null;
    TreeNode second = null;
    TreeNode prev = new TreeNode(Integer.MIN_VALUE);
    public void recoverTree(TreeNode root) {
        traverse(root);
        
        //swap
        int temp = first.val;
        first.val = second.val;
        second.val = temp;
    }
    
    private void traverse(TreeNode root){
        if(root == null) return;
        traverse(root.left);
        //swap the prev and root
        if(first == null && prev.val>root.val) first = prev;
        if(first!=null && prev.val>root.val) second = root;
        
        prev = root;
        
        traverse(root.right);
        
    }
}

你可能感兴趣的:(99. Recover Binary Search Tree)