来到当前节点cur,cur为头节点
1.如果cur没有左子树,cur右移 cur = cur->right
2.如果cur有左子树,找到左子树的最右节点mostright
1)如果mostright指向NULL,将mostright指向cur,并且cur左移
2)如果mostright指向cur,将mostright指向NULL,并且cur右移
3.cur遍历为NULL为止
class Solution {
public:
vector<int> morris(TreeNode* root) {
while(root != NULL)
{
TreeNode* mostright = root->left;
if(mostright != NULL)
{
while(mostright->right != NULL && mostright->right != root)
{
mostright = mostright->right;
}
if(mostright->right == NULL)
{
result.push_back(root->val);
mostright->right = root;
root = root->left;
continue;
}else
{
mostright->right = NULL;//来到这一步之后再往下就是第二次来的节点
}
}
root = root->right;
}
return result;
}
};
前序遍历
该节点只来一次,直接打印
该节点来两次,第一次来就打印
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if(root == NULL)
{
return result;
}
while(root != NULL)
{
TreeNode* mostright = root->left;
if(mostright != NULL)
{
while(mostright->right != NULL && mostright->right != root)
{
mostright = mostright->right;//第一次来这个节点
}
if(mostright->right == NULL)
{
result.push_back(root->val);
mostright->right = root;
root = root->left;
continue;
}else
{
mostright->right = NULL;//来到这一步之后再往下就是第二次来的节点
}
}else{
result.push_back(root->val);//左子树为空只来这个节点一次
}
root = root->right;
}
return result;
}
};
中序遍历
该节点只来一次,直接打印
该节点来两次,第二次来打印
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
if(root == NULL)
{
return result;
}
while(root != NULL)
{
TreeNode* mostright = root->left;
if(mostright != NULL)
{
while(mostright->right != NULL && mostright->right != root)
{
mostright = mostright->right;
}
if(mostright->right == NULL)
{
mostright->right = root;
root = root->left;
continue;
}else
{
mostright->right = NULL;
}
}
result.push_back(root->val);// 左子树为空(只到一次)或者 第二次到某节点
root = root->right;
}
return result;
}
};
后序遍历
第二次到这个节点时将左子树的右边界逆序打印
最后将头节点的右边界逆序打印
class Solution {
public:
TreeNode* next = NULL;
TreeNode* pre = NULL;
TreeNode* reverseTree(TreeNode* from)
{
next = NULL;
pre = NULL;
while(from != NULL)
{
next = from->right;
from->right = pre;
pre = from;
from = next;
}
return pre;
}
void reversePrintf(TreeNode* root, vector<int>& result)
{
TreeNode* temp = reverseTree(root);
TreeNode *cur = temp;
while(cur != NULL)
{
result.push_back(cur->val);
cur = cur->right;
}
reverseTree(temp);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root == NULL)
{
return result;
}
TreeNode* cur = root;
while(cur != NULL)
{
TreeNode* mostright = cur->left;
if(mostright != NULL)
{
while(mostright->right != NULL && mostright->right != cur)
{
mostright = mostright->right;
}
if(mostright->right == NULL)
{
mostright->right = cur;
cur = cur->left;
continue;
}else
{
mostright->right = NULL;
reversePrintf(cur->left, result);//左子树的右边界去逆序打印
}
}
cur = cur ->right;
}
reversePrintf(root, result);//头节点右边界逆序打印
return result;
}
};