1. 程式人生 > >Recover Binary Search Tree(恢復二叉搜尋樹)

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?

基本思路:

這個題的意思就是一個二叉查詢樹有兩個元素被調換了順序,此時需要修復成二叉查詢樹。基於此,由於構成二叉查詢樹的序列是二叉樹的中序遍歷序列,所以一旦我們根據中序遍歷找到兩個“變動”的點然後交換他們的值即可。

	TreeNode pre = null;//始終指向中序遍歷的上一個節點
	TreeNode n1 = null;//記錄待交換節點
	TreeNode n2 = null;//記錄帶交換節點
	
	public TreeNode recoverTree(TreeNode root)
	{
		findTwoNode(root);
		
		if(n1!=null&&n2!=null)
		{
			int tmp = n1.val;
			n1.val = n2.val;
			n2.val = tmp;
		}
		return root;
	}
	
	
	public void findTwoNode(TreeNode root)
	{
		if(root==null)
			return;
		findTwoNode(root.left);
		if(pre!=null&&pre.val>root.val)
		{
			if(n1==null)
				n1 = pre;
			n2 = root;
		}
		pre = root;
		findTwoNode(root.right);
	}