您的位置:首页 > 其它

Recover Binary Search Tree - LeetCode

2014-02-22 11:57 537 查看
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.

Discuss

重点在中序遍历,注意这一步 
if (prev != null && prev.val > root.val) {
if (first == null) {
first = prev;
}

second = root;
}

以下是AC代码:

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {

private TreeNode first;
private TreeNode second;
private TreeNode prev;

public void recoverTree(TreeNode root) {
if (root == null) {
return;
}

first = null;
second = null;
prev = null;

recoverTreeHelper(root);
switchValue(first, second);
}

private void switchValue(TreeNode node1, TreeNode node2) {
int val = node1.val;
node1.val = node2.val;
node2.val = val;
}

private void recoverTreeHelper(TreeNode root) {
if (root == null) {
return;
}

recoverTreeHelper(root.left);

if (prev != null && prev.val > root.val) { if (first == null) { first = prev; } second = root; }
prev = root;
recoverTreeHelper(root.right);
}

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