LeetCode 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?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as  "{1,2,3,#,#,4,#,#,5}".
题意:任意交换一次搜索树上的两个节点,让你再复原回去。

思路:我们都知道中序遍历树的话就会是一个递增的序列,那么如果交换的节点刚好相邻的话,那么我们记录然后交换一下就行了,但是如果两个数是不相邻的话,比如说:12345,交换了1和5,->52341,那么这个序列就存在了两个逆序对,52,和41,那么我们记录第一次出现的第一个,第二次出现的第二个,也就是5和1,那么交换就行了。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
  private TreeNode preNode = null;
	
	private void cal(TreeNode root, List res) {
		if (root == null) return;
		cal(root.left, res);
		if (preNode != null && preNode.val > root.val) {
			if (res.size() == 0) {
				res.add(preNode);
				res.add(root);
			} else {
				res.set(1, root);
			}
		}
		preNode = root;
		cal(root.right, res);
	}
	
	public void recoverTree(TreeNode root) {  
		if (root == null) return;
		List res = new ArrayList();
		cal(root, res);
		
		if (res.size() > 0) {
			int tmp = res.get(0).val;
			res.get(0).val = res.get(1).val;
			res.get(1).val = tmp;
		}
	} 	
}


你可能感兴趣的:(LeetCode与面试题)