# leetcode -day27 Recover Binary Search Tree & Interleaving String

66 篇文章 0 订阅
1、
﻿﻿

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?

class Solution {
public:
TreeNode* preNode;
TreeNode* node1;
TreeNode* node2;
void recoverTree(TreeNode *root) {
preNode = NULL;
node1 = NULL;
node2 = NULL;
recursiveTree(root);
if(node1 && node2){
int temp = node1->val;
node1->val = node2->val;
node2->val = temp;
}
}
void recursiveTree(TreeNode *root){
if(!root){
return;
}
if(root->left){
recursiveTree(root->left);
}
if(preNode && root->val < preNode->val){
if(node1){
node2 = root;
}else{
node1 = preNode;
node2 = root;
}
}
preNode = root;
if(root->right){
recursiveTree(root->right);
}
}
};

2、Interleaving String

Given s1s2s3, find whether s3 is formed by the interleaving of s1 and s2.

For example,
Given:
s1 = "aabcc",
s2 = "dbbca",

When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.

class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {

bool **f = new bool*[s1.size()+1];
for(int i=0; i<=s1.size(); ++i){
f[i] = new bool[s2.size()+1];
}
if (s1.size() + s2.size() != s3.size())
return false;

f[0][0] = true;
for(int i = 1; i <= s1.size(); i++)
f[i][0] = f[i-1][0] && (s3[i-1] == s1[i-1]);

for(int j = 1; j <= s2.size(); j++)
f[0][j] = f[0][j-1] && (s3[j-1] == s2[j-1]);

for(int i = 1; i <= s1.size(); i++)
for(int j = 1; j <= s2.size(); j++)
f[i][j] = (f[i][j-1] && s2[j-1] == s3[i+j-1]) || (f[i-1][j] && s1[i-1] == s3[i+j-1]);
bool result = f[s1.size()][s2.size()];
for(int i=0; i<=s1.size(); ++i){
delete[] f[i];
}
delete[] f;
return result;
}
};

01-02 306
07-03 2457

04-13 9788
04-10 895
04-02 2714
08-14 307
05-29 1573
01-05 3240
05-14 2139
02-04 416
03-24 432
05-29 912
08-02 79
04-03 89
03-20 4058
05-17 3110

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

xiao囡囡

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。