001 递归调用
class Solution {
public:
void inOrder(TreeNode* root, vector<int>&ans){
if (root) {
inOrder(root->left,ans);
ans.push_back(root->val);
inOrder(root->right,ans);
}
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int>ans;
inOrder(root,ans);
return ans;
}
};
002 栈
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>ans;
stack<TreeNode *> s;
//这里判断的条件是 root 和 s 不为空
while (root || !s.empty()) {
while (root) {
s.push(root);
root = root->left;
}
//到达最左边 把结点弹出来 进行遍历
root = s.top();
s.pop();
//将值放入集合中
ans.push_back(root->val);
//转向右子树
root = root->right;
}
return ans;
}
};
003 Mirros
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>ans;
auto cur = root;
while (cur) {
if (cur->left) {
auto pre = cur->left;
while (pre->right && pre->right !=cur) {
pre = pre->right;
}
if (!pre->right) {
pre->right = cur;
cur = cur->left;
}else{
ans.push_back(cur->val);
pre->right = nullptr;
cur = cur->right;
}
}else{
ans.push_back(cur->val);
cur = cur->right;
}
}
return ans;
}
};