中序遍历:递归
/*
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 == nullptr) {
return nullptr;
}
Convert(pRootOfTree->left);
if (pre == nullptr) {
head = pRootOfTree;
pre = pRootOfTree;
} else {
pre->right = pRootOfTree;
pRootOfTree->left = pre;
pre = pRootOfTree;
}
Convert(pRootOfTree->right);
return head;
}
private:
TreeNode *head = nullptr;
TreeNode *pre = nullptr;
};
栈: 这里注意循环的终止条件
/*
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 == nullptr) {
return nullptr;
}
Convert(pRootOfTree->left);
if (pre == nullptr) {
head = pRootOfTree;
pre = pRootOfTree;
} else {
pre->right = pRootOfTree;
pRootOfTree->left = pre;
pre = pRootOfTree;
}
Convert(pRootOfTree->right);
return head;
}
private:
TreeNode *head = nullptr;
TreeNode *pre = nullptr;
};