Leetcode.94.二叉树的中序遍历
94.二叉树的中序遍历
递归遍历
迭代遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> lt;
vector<int> ans;
TreeNode* curr = root;
while(!lt.empty() || curr!=nullptr){
while(curr != nullptr){
lt.push(curr);
curr=curr->left;
}
TreeNode* p = lt.top();
lt.pop();
ans.push_back(p->val);
if(p->right != nullptr)
{
curr = p->right;
}
}
return ans;
}
};
莫里斯遍历
莫里斯遍历主要思想是将中间根节点放到左子树的最右侧节点。
可以从运行时间和使用内存看出来,确实莫里斯遍历要由于普通迭代。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
TreeNode* curr=root;
while(curr!=nullptr)
{
if(curr->left == nullptr){
ans.push_back(curr->val);
curr=curr->right;
}
else{
TreeNode* p = curr->left;
while(p->right!=nullptr){
p=p->right;
}
p->right= curr;
TreeNode* t=curr;
curr = curr->left;
t->left = nullptr;
}
}
return ans;
}
};