码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Recover Binary Search Tree

时间:2015-04-25 21:15:52      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

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<TreeNode> 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<TreeNode> res = new ArrayList<TreeNode>();
		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 Recover Binary Search Tree

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45273973

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!