Recursion
Preorder traversal
/**
* 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:
void traversal(TreeNode* cur,vector<int>&vec)//传引用
{
if(cur==NULL) return;
vec.push_back(cur->val);//根
traversal(cur->left,vec);//左
traversal(cur->right,vec);//右
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int>result;
traversal(root,result);
return result;
}
};
In-order traversalwithPost-order traversalThe realization of is also very simple, just change the order in the pre-order traversal.
Iterative method
In recursion, a stack is hidden. In the iterative method, the stack needs to be displayed explicitly.
Preorder traversal
/**
* 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> result;
stack<TreeNode*> st;
st.push(root);
while(!st.empty())
{
TreeNode* cur=st.top();//访问栈顶元素
st.pop();//弹出栈顶元素
if(cur!=NULL) //当栈顶元素不为空时(没访问到叶子结点时)
result.push_back(cur->val);
else //若栈顶元素为空(遇到叶子结点)
continue;
st.push(cur->right);//右子树结点先入栈
st.push(cur->left);
}
return result;
}
};
Post-order traversal
The post-order traversal only needs to be slightly modified on the basis of the pre-order traversal.
The pre-order traversal is: root, left, and right, and the final post-order traversal is: left, right, and root.
Idea: In the preorder traversal, change to root, right, and left, and then reverse the order in the vector.
In-order traversal
The middle order traversal is different from the other two, the stacking order is inconsistent, the code first
/**
* 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> result;
stack<TreeNode*> st;
TreeNode* cur=root;
while(cur!=NULL || !st.empty())
{
if(cur!=NULL)
{
st.push(cur);
cur=cur->left;
}
else
{
cur=st.top();
st.pop();
result.push_back(cur->val);
cur=cur->right;
}
}
return result;
}
};
Visit the current node, if it is not empty, visit its left node, if it is empty but the stack is not empty at this time, visit the top element of the stack, and then visit its right node.