首页 > 其他 > 详细

LeetCode | Recover Binary Search Tree

时间:2014-03-03 09:45:11      阅读:469      评论: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?

分析

根据对BST中序遍历结果的升序特性,可以找到逆序对,这里要注意两种情况:

1. 如果交换节点刚好在中序遍历时,是相邻的,那么只有一个逆序对;

2. 如果不相邻,就有两个逆序对

代码

public class RecoverBinarySearchTree {
	private TreeNode first;
	private TreeNode second;
	private TreeNode preNode;

	public void recoverTree(TreeNode root) {
		first = null;
		second = null;
		preNode = null;
		inorder(root);
		assert first != null && second != null;
		int temp = first.val;
		first.val = second.val;
		second.val = temp;
	}

	private void inorder(TreeNode root) {
		if (root == null) {
			return;
		}
		inorder(root.left);
		if (preNode != null && root.val < preNode.val) {
			if (first == null) {
				first = preNode;
			}
			second = root;
		}
		preNode = root;
		inorder(root.right);
	}
}


LeetCode | Recover Binary Search Tree,布布扣,bubuko.com

LeetCode | Recover Binary Search Tree

原文:http://blog.csdn.net/perfect8886/article/details/20283487

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!