您的位置:首页 > 其它

Recover Binary Search Tree

2015-01-26 19:30 369 查看


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.

Java代码:

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode firstElement = null;
TreeNode secondElement = null;
// The reason for this initialization is to avoid null pointer exception in the first comparison when prevElement has not been initialized
TreeNode prevElement = new TreeNode(Integer.MIN_VALUE);

public void recoverTree(TreeNode root) {

// In order traversal to find the two elements
traverse(root);

// Swap the values of the two nodes
int temp = firstElement.val;
firstElement.val = secondElement.val;
secondElement.val = temp;
}

private void traverse(TreeNode root) {

if (root == null)
return;

traverse(root.left);

// Start of "do some business",
// If first element has not been found, assign it to prevElement (refer to 6 in the example above)
if (firstElement == null && prevElement.val >= root.val) {
firstElement = prevElement;
}

// If first element is found, assign the second element to the root (refer to 2 in the example above)
if (firstElement != null && prevElement.val >= root.val) {
secondElement = root;
}
prevElement = root;

// End of "do some business"

traverse(root.right);
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: