- 前序遍历
/**
* 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> res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* tmp = st.top();
st.pop();
if(tmp==NULL)
continue;
res.push_back(tmp->val);
st.push(tmp->right);
st.push(tmp->left);
}
return res;
}
};
- 中序遍历
/**
* 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> res;
stack<TreeNode*> st;
while(root!=NULL || !st.empty()){
while(root!=NULL){
st.push(root);
root = root->left;
}
root = st.top();
st.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
//递归求中序遍历:左根右
void fun(vector<int>& res, TreeNode* root)
{
if(root==NULL)
return;
fun(res, root->left);
res.push_back(root->val);
fun(res, root->right);
}
};
- 后序遍历
/**
* 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> res;
if(root==NULL)
return res;
stack<TreeNode*> st;
TreeNode* pre = NULL;
while(root || !st.empty()){
while(root){
st.push(root);
root = root->left;
}
root = st.top();
st.pop();
if(root->right==NULL || root->right==pre){
res.push_back(root->val);
pre = root;
root = NULL;
}
else {
st.push(root);
root = root->right;
}
}
return res;
}
//递归:左右根
void fun(vector<int> &res, TreeNode* root)
{
if(root==NULL)
return;
fun(res, root->left);
fun(res, root->right);
res.push_back(root->val);
}
};