题目
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?
思路
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!root)
return ;
vector<int> myvector;
midOrder(root,myvector);
int len = myvector.size();
int first = 0;
int i=0;
while(i<len-1)
{
if(myvector[i]>=myvector[i+1])
{
first = i;
break;
}
i++;
}
int second = first+1;
int j = first+1;
while(j<len-1)
{
if(myvector[j]>=myvector[j+1])
{
second = j+1;
break;
}
j++;
}
midOrderVal(root,myvector[first],myvector[second]);
}
void midOrder(TreeNode *root, vector<int> &myvector) {
if(!root)
return ;
midOrder(root->left,myvector);
myvector.push_back(root->val);
midOrder(root->right,myvector);
}
void midOrderVal(TreeNode *root, int firstval, int secondval) {
if(!root)
return ;
midOrderVal(root->left,firstval,secondval);
if(root->val==firstval)
{
root->val = secondval;
}
else if(root->val==secondval)
{
root->val = firstval;
}
midOrderVal(root->right,firstval,secondval);
}
};
最新 java
/**
* 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 = null;
private TreeNode first = null;
private TreeNode second = null;
public void recoverTree(TreeNode root) {
if(root == null){
return;
}
inorder(root);
int temp = first.val;
first.val = second.val;
second.val = temp;
}
private void inorder(TreeNode root){
if(root == null){
return;
}
inorder(root.left);
if(pre != null && pre.val >= root.val){
if(first == null){
first = pre;
second = root;
} else {
second = root;
}
}
pre = root;
inorder(root.right);
}
}
327

被折叠的 条评论
为什么被折叠?



