二叉树的前中后序遍历的 moris写法。
作者:
上将邢道荣
,
2021-11-24 11:43:00
,
所有人可见
,
阅读 187
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
//二叉树的前序遍历 moris写法。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if (!root) return res;
while (root) {
if (root->left) {
auto p = root->left;
while (p->right && p->right != root) p = p->right;
if (!p->right) {
res.push_back(root->val);
p->right = root;
root = root->left;
} else {
p->right = NULL;
root = root->right;
}
} else {
res.push_back(root->val);
root = root->right;
}
}
return res;
}
};
// 二叉树的中序遍历 moris写法
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
auto cur = root;
while (cur) {
if (cur->left) {
auto l = cur->left;
while (l->right && l->right != cur) l = l->right;
if (!l->right) {
l->right = cur;
cur = cur->left;
} else {
res.push_back(cur->val);
l->right = NULL;
cur = cur->right;
}
} else {
res.push_back(cur->val);
cur = cur->right;
}
}
return res;
}
};
// 二叉树的后续遍历 moris写法。
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if (!root) return res;
while (root) {
if (root->right) {
auto p = root->right;
while (p->left && p->left != root) p = p->left;
if (!p->left) {
res.push_back(root->val);
p->left = root;
root = root->right;
} else {
p->left = NULL;
root = root->left;
}
} else {
res.push_back(root->val);
root = root->left;
}
}
reverse(res.begin(), res.end());
return res;
}
};