首页 > 其他 > 详细

Recover Binary Search Tree

时间:2015-08-26 02:26:15      阅读:220      评论: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.

?

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	private TreeNode pre;
	private TreeNode first;
	private TreeNode second;
	public void inorder(TreeNode root){
		if (root == null) {
			return;
		}
		inorder(root.left);
		if (pre == null) {
			pre = root;
		} else {
			if (pre.val >= root.val) {
				if (first == null) {
					first = pre;
				}
				second = root;
			}
			pre = root;
		}
		inorder(root.right);
	}
    public void recoverTree(TreeNode root) {
    	inorder(root);
    	if (first!=null && second!=null) {
    		int tmp = first.val;
    		first.val = second.val;
    		second.val = tmp;
    	}
    }
}

?

Recover Binary Search Tree

原文:http://hcx2013.iteye.com/blog/2237444

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