`
hcx2013
  • 浏览: 88904 次
社区版块
存档分类
最新评论

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.

 

/**
 * 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;
    	}
    }
}

 

1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics