中序遍历:左–根--右
利用栈
struct Command{
public:
string s;//"go" "print"
TreeNode* node;
Command(string s, TreeNode* node) : s(s), node(node){}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr) return res;
stack<Command> s;
s.push(Command("go", root));
while(!s.empty()){
Command tmp = s.top(); s.pop();
TreeNode* t = tmp.node;
if(tmp.s == "print"){
res.push_back(t->val);
}else{
if(t->right){
s.push(Command("go", t->right));
}
s.push(Command("print", t));
if(t->left){
s.push(Command("go", t->left));
}
}
}
return res;
}
};
Morris遍历,O(1)的空间复杂度实现二叉树的中序遍历。
解析
class Solution {
TreeNode* getLeftMostRight(TreeNode* root){
TreeNode* node = root->left;
while(node && node->right && node->right != root){
node = node->right;
}
return node;
}
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
while(root){
//当左子树为空,或者第二次访问到该节点的时候,打印
//左边处理完了,可以右移了
if(root->left == nullptr){
res.push_back(root->val);
root = root->right;
}else{
TreeNode* node = getLeftMostRight(root);
if(node->right == nullptr){ //第一次访问
node->right = root;
root = root->left;
}else{
res.push_back(root->val);
node->right = nullptr; //恢复
root = root->right;
}
}
}
return res;
}
};