See how Fed stabs taxpayers in the back (转载)# Stock
a*e
1 楼
知道要O(1)space的得用Morris Traversal。但想先写个简单的,却发现改了好几次。
1。 开始没想清楚怎么把那两个错误的node找出来
2. 应该用*& 的地方用了*。 后来发现不作为param来pass还更简单。
但这样也有很多行,等有时间写个Morris的比较下。感觉也不是那么简单啊,sigh!
class Solution {
public:
TreeNode *first, *second, *pre;
void helper(TreeNode *cur)
{
if (cur==NULL)
return;
helper(cur->left);
if (pre)
{
if (pre->val>cur->val)
{
if (first==NULL)
{
first = pre;
second = cur;
}
else
second = cur;
}
}
pre = cur;
helper(cur->right);
}
void recoverTree(TreeNode *root) {
if (root==NULL||(root->left==NULL && root->right==NULL))
{
return;
}
first=NULL, second=NULL, pre=NULL;
helper(root);
int tmp = first->val;
first->val = second->val;
second->val = tmp;
}
之前pass param的
class Solution {
public:
void helper(TreeNode *cur, TreeNode *&first, TreeNode *&second, TreeNode
*&pre)
{
if (cur==NULL)
return;
helper(cur->left, first, second, pre);
if (pre)
{
if (pre->val>cur->val)
{
if (first==NULL)
{
first = pre;
second = cur;
}
else
second = cur;
}
}
pre = cur;
helper(cur->right, first, second, pre);
}
void recoverTree(TreeNode *root) {
if (root==NULL||(root->left==NULL && root->right==NULL))
{
return;
}
vector t;
TreeNode *first=NULL, *second=NULL, *pre=NULL;
helper(root,first, second, pre);
int tmp = first->val;
first->val = second->val;
second->val = tmp;
}
};
1。 开始没想清楚怎么把那两个错误的node找出来
2. 应该用*& 的地方用了*。 后来发现不作为param来pass还更简单。
但这样也有很多行,等有时间写个Morris的比较下。感觉也不是那么简单啊,sigh!
class Solution {
public:
TreeNode *first, *second, *pre;
void helper(TreeNode *cur)
{
if (cur==NULL)
return;
helper(cur->left);
if (pre)
{
if (pre->val>cur->val)
{
if (first==NULL)
{
first = pre;
second = cur;
}
else
second = cur;
}
}
pre = cur;
helper(cur->right);
}
void recoverTree(TreeNode *root) {
if (root==NULL||(root->left==NULL && root->right==NULL))
{
return;
}
first=NULL, second=NULL, pre=NULL;
helper(root);
int tmp = first->val;
first->val = second->val;
second->val = tmp;
}
之前pass param的
class Solution {
public:
void helper(TreeNode *cur, TreeNode *&first, TreeNode *&second, TreeNode
*&pre)
{
if (cur==NULL)
return;
helper(cur->left, first, second, pre);
if (pre)
{
if (pre->val>cur->val)
{
if (first==NULL)
{
first = pre;
second = cur;
}
else
second = cur;
}
}
pre = cur;
helper(cur->right, first, second, pre);
}
void recoverTree(TreeNode *root) {
if (root==NULL||(root->left==NULL && root->right==NULL))
{
return;
}
vector
TreeNode *first=NULL, *second=NULL, *pre=NULL;
helper(root,first, second, pre);
int tmp = first->val;
first->val = second->val;
second->val = tmp;
}
};