当前位置:网站首页>LeetCode145. Post order traversal of binary tree (three methods of recursion and iteration)
LeetCode145. Post order traversal of binary tree (three methods of recursion and iteration)
2022-07-05 22:54:00 【Qingshan's green shirt】
LeetCode145. Postorder traversal of binary trees
List of articles
1. problem

2. Ideas
(1) What is post order traversal

(2) recursive
It's the same as the previous sequence and the middle sequence , Just put the root node to the last access
(3) Iterative thinking
a. Transform preorder traversal

b. Fake middle root traversal
Middle root traversal :1. From the root node From top to bottom Go down the left branch , And put the nodes along the way Pressing stack , Until the deepest node ( No left child ).
2. Follow the left passage , Play the stack from bottom to top , Sequential access All nodes along the way And its Right subtree .
As shown in the figure below :
The post order traversal faces a problem : Behind the bomb stack , Cannot access immediately p, But first visit p The right subtree , And then visit p. So it needs to be preserved in some way p.
Strategy 1: Don't talk about stack p, Instead, only take the value of the element at the top of the stack .
Strategy 2: Allow nodes to enter and leave the stack multiple times , Instant bomb stack p Then let it enter the stack immediately .
Strategy 1

Strategy 2:
Set a binary in the stack element , Maintain a label i,i Represents the current node / Stack times . Any node in a binary tree p You have to enter the stack three times , Out of stack three times .
The first time out of the stack is for traversal p The left subtree .
The second battle is for traversal p The right subtree .
The third time is to access p.


Operation example
Pseudo code 
3. Code implementation
(1) recursive
class Solution
{
public:
void posOrder(TreeNode*cur,vector<int>& vec)
{
if(cur == NULL)return;
posOrder(cur->left,vec);// Left
posOrder(cur->right,vec);// Right
vec.push_back(cur->val);// root
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
posOrder(root, result);
return result;
}
};
(2) iteration
a. Transform preorder traversal
class Slution{
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*>st;
vector<int> result;
if(root == NULL) return result;
st.push(root);
while(!st.empty()){
TreeNode* node = st.pop();
st.pop();
result.push_nack(node->val);
if(node->left st.push(node->left));// Relative to the previous sequence traversal, make a change here
if(node->right) st.push(node->right);// Empty nodes do not stack
}
reverse(result.begin(),result.end());// The reverse result is the order of left and right
return result;
}
};
b. Strategy 1
class Solution{
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*>st;
vector<int> result;
TreeNode* p = root;
TreeNode* pre = NULL;// pre yes p After the root of the precursor , That is to say p Previously visited nodes
while(1){
while(p!=NULL){
st.push(p);
p = p->left;
}
if(st.empty()) return result;
p = st.top();
if(p!=NULL){
if( p->right == NULL||pre == p->right)
{
p = st.top();st.pop();
result.push_back(p->val);
pre = p; p = NULL;
}
else p = p->right;
}
}
}
};
b. Strategy 2
Use STL:
class Solution{
public:
vector<int> postorderTraversal(TreeNode* root) {
int flag[512];
int top = 0;//top Point to the position where the element will be placed It really doesn't work because stl There is no change in top
stack<TreeNode*>st;
vector<int> result;
flag[top] = 1;
st.push(root);
top++;
while(!st.empty()){
TreeNode* p = st.top();
st.pop();// Out of the stack
top--;
if(flag[top] == 1){
flag[top] = 2; st.push(p); top++;
if(p!= NULL && p->left != NULL)
{
flag[top] = 1;
st.push(p->left);
top++;
}
}
else if(flag[top] == 2)
{
flag[top] = 3; st.push(p);top++;
if(p!=NULL && p->right != NULL){
flag[top] = 1;
st.push(p->right);
top++;
}
}
else if(p!=NULL && flag[top] == 3)
result.push_back(p->val);
}
return result;
}
};
Be careful !top It needs to be maintained additionally !stl There's no such thing as int top This kind of thing !
Don't use STL:
int flag[512];
int top = 0;//top Point to the position where the element will be placed
class stac{
public:
void InitStack(){
top = 0;
}
void Push(TreeNode *p){
stack[top++] = p;
}
TreeNode* Pop(){
top--;
return stack[top];
}
bool empty() {
if (top == 0)return true;
return false;
}
TreeNode* Top( ){
return stack[top-1];
}
private:
TreeNode *stack[512];
};
class Solution{
public:
vector<int> postorderTraversal(TreeNode* root) {
stac st;
st.InitStack();
vector<int> result;
flag[top] = 1;
st.Push(root);
while(!st.empty()){
TreeNode* p = st.Pop();// Out of the stack
if(flag[top] == 1){
flag[top] = 2; st.Push(p);
if(p!= NULL && p->left != NULL)
{
flag[top] = 1;
st.Push(p->left);
}
}
else if(flag[top] == 2)
{
flag[top] = 3; st.Push(p);
if(p!=NULL && p->right != NULL){
flag[top] = 1;
st.Push(p->right);
}
}
else if(p!=NULL && flag[top] == 3)
{
result.push_back(p->val);
}
else
continue;
}
return result;
}
};
边栏推荐
- [digital signal denoising] improved wavelet modulus maxima digital signal denoising based on MATLAB [including Matlab source code 1710]
- [error record] file search strategy in groovy project (src/main/groovy/script.groovy needs to be used in the main function | groovy script directly uses the relative path of code)
- Assign the output of a command to a variable [repeat] - assigning the output of a command to a variable [duplicate]
- TCC of distributed solutions
- Selenium+Pytest自动化测试框架实战
- fibonacci search
- Global and Chinese markets for reciprocating seal compressors 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese market of networked refrigerators 2022-2028: Research Report on technology, participants, trends, market size and share
- Business introduction of Zhengda international futures company
- Methods modified by static
猜你喜欢

Masked Autoencoders Are Scalable Vision Learners (MAE)

openresty ngx_lua请求响应

The difference between MVVM and MVC

南京:全面启用商品房买卖电子合同

Post-90s tester: "after joining Ali, this time, I decided not to change jobs."

My experience and summary of the new Zhongtai model

Common JVM tools and optimization strategies

Exponential weighted average and its deviation elimination

Editor extensions in unity

我把开源项目alinesno-cloud-service关闭了
随机推荐
2022 Software Test Engineer salary increase strategy, how to reach 30K in three years
Three.JS VR看房
Methods modified by static
Global and Chinese market of diesel fire pump 2022-2028: Research Report on technology, participants, trends, market size and share
Function default parameters, function placeholder parameters, function overloading and precautions
fibonacci search
I closed the open source project alinesno cloud service
Global and Chinese markets for welding products 2022-2028: Research Report on technology, participants, trends, market size and share
opencv 判断点在多边形内外
Double pointeur de liste liée (pointeur rapide et lent, pointeur séquentiel, pointeur de tête et de queue)
Paddy serving v0.9.0 heavy release multi machine multi card distributed reasoning framework
傅里叶分析概述
查看网页最后修改时间方法以及原理简介
H5c3 advanced - player
Distance entre les points et les lignes
One article deals with the microstructure and instructions of class
d3dx9_ How to repair 31.dll_ d3dx9_ 31. Solution to missing DLL
Double pointer of linked list (fast and slow pointer, sequential pointer, head and tail pointer)
Roman numeral to integer
VIM tail head intercept file import