三道题分别二叉树的前序、中序、后序遍历,这次使用非递归方法解决。
首先是前序,一直走左边进栈,到底之后走栈顶的右子结点,因为每次先遍历root,所以入栈的时候就将结点push进路径数组中。
//qianxu
/**
* 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) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> v;
if (root == nullptr) return v;
stack<TreeNode*> s;
TreeNode* p = root;
while (!s.empty() || p != nullptr) {
while (p != nullptr) {
s.push(p);
v.push_back(p->val);
p = p->left;
}
if (!s.empty()) {
p = s.top();
s.pop();
p = p->right;
}
}
return v;
}
};
然后是中序遍历,和前序遍历基本一样,只是每次将栈顶push进路径数组中,因为与DFS顺序一样。
//zhongxu
/**
* 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) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> v;
if (root == nullptr) return v;
stack<TreeNode*> s;
TreeNode *p = root;
while (!s.empty() || p != nullptr) {
while (p != nullptr) {
s.push(p);
p = p->left;
}
if (!s.empty()) {
p = s.top();
v.push_back(p->val);
s.pop();
p = p->right;
}
}
return v;
}
};
后序遍历麻烦一些,总体思想为,入栈的顺序(遍历的反顺序)为先左节点再右节点,然后每次取栈顶进入另一个栈(此栈为路径数组的逆顺序)执行上述操作。
//houxu
/**
* 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) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> v;
if (root == nullptr) return v;
stack<TreeNode*> src;
stack<TreeNode*> res;
src.push(root);
while (!src.empty()) {
TreeNode* p = src.top();
src.pop();
res.push(p);
if (p->left != nullptr) src.push(p->left);
if (p->right != nullptr) src.push(p->right);
}
while (!res.empty()) {
TreeNode* p = res.top();
res.pop();
v.push_back(p->val);
}
return v;
}
};
|