使用递归,分四种情况讨论即可
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree)
{
if (pRootOfTree == NULL) {
return NULL;
} else if (pRootOfTree->left == NULL && pRootOfTree->right == NULL) {
return pRootOfTree;
} else if (pRootOfTree->left == NULL) {
TreeNode* r = Convert(pRootOfTree->right);
pRootOfTree->right = r;
r->left = pRootOfTree;
return pRootOfTree;
} else if (pRootOfTree->right == NULL) {
TreeNode* l = Convert(pRootOfTree->left);
TreeNode* temp = l;
while (l->right) {
l = l->right;
}
pRootOfTree->left = l;
l->right = pRootOfTree;
return temp;
}
else if (pRootOfTree) {
TreeNode* l = Convert(pRootOfTree->left);
TreeNode* r = Convert(pRootOfTree->right);
TreeNode* temp_l = l;
while (l->right) {
l = l->right;
}
pRootOfTree->left = l;
l->right = pRootOfTree;
pRootOfTree->right = r;
r->left = pRootOfTree;
return temp_l;
}
}
};