leetCode练习(99)

题目:Recover Binary Search Tree

难度:hard

问题描述:

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?

解题思路:

很容易想到搜索二叉树的中序遍历是有序数列。如果遍历结果是1、8、4、5、7、3、10,则知道是第二个结点和第6个结点反掉了。 因此我们可以在中序遍历输出的地方进行判断,如果是错误节点,就保留该节点。具体代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode t1,t2;
	TreeNode pre=new TreeNode(Integer.MIN_VALUE);
    public void recoverTree(TreeNode root) {
        bfs(root);
		int temp=t1.val;
		t1.val=t2.val;
		t2.val=temp;
    }
    private void bfs(TreeNode root) {
		if(root==null){
			return;
		}
		bfs(root.left);
		//中序遍历中间处理
		if(t1==null&&pre.val>=root.val){
			t1=pre;
		}
		if(t1!=null&&pre.val>=root.val){
			t2=root;
		}
		pre=root;
		//处理结束		
		bfs(root.right);		
		
    }
}

你可能感兴趣的:(leetCode)