Recover Binary Search Tree (Java)

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?

這道題的意思是需要將BST樹中兩個因錯誤交換的結點的值糾正過來。只需要交換值即可。

中序遍歷,如果是正確的BST結果應該是非降序的,用pre和當前值比較,整個數列中有兩次pre > 當前值root的情況(錯誤發生點)。 前一次取pre,後一次取root,交換這兩個值即可。

Source

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	TreeNode pre;
	TreeNode a, b;
    public void recoverTree(TreeNode root) {
        if(root == null) return;
        pre = null;
        a = null;
        b = null;
        inorder(root);
        if(a != null && b != null){
        	int temp = a.val;
        	a.val = b.val;
        	b.val = temp;
        }
    }
    public void inorder(TreeNode root){
    	if(root == null) return;
    	inorder(root.left);
    	if(pre == null){
    		pre = root;  //如果pre置爲root.left,而left又是null時是無法取pre.val的
    	}
    	else{
    		if(pre.val > root.val){
    			if(a == null){
    				a = pre;
    			}
    			b = root;  //a是序列中第一個出現降序的開始,b是a後面第一個降序的結尾 即序列中只有兩次pre > root 一次取pre 一次取root即可
    		}
    		pre = root;
    	}
    	inorder(root.right);
    }
}


Test

    public static void main(String[] args){
    	TreeNode a = new TreeNode(2);
    	a.left = new TreeNode(3);
    	a.right = new TreeNode(1);
    	new Solution().recoverTree(a);
    	System.out.println(a.left.val);
    	System.out.println(a.right.val);
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章