前序、中序、后续非递归、递归版本
//后序-非递归版本
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
while(root || !st.empty()) {
if (root) {
st.push(root);
//前插字符,根右左顺序
res.insert(res.begin(), root->val);
root = root->right;
} else {
TreeNode* temp = st.top();
st.pop();
root = temp->left;
}
}
return res;
}
//后续-递归版本
void dfs(TreeNode* root, vector<int> &res) {
if (root->left) {
dfs(root->left, res);
}
if (root->right) {
dfs(root->right, res);
}
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if (root == NULL) {
return res;
}
dfs(root, res);
return res;
}
//前序-非递归版本
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> res;
while(root || !st.empty()) {
if (root) {
res.push_back(root->val);
st.push(root);
root = root->left;
} else {
TreeNode* temp = st.top();
st.pop();
root = temp->right;
}
}
return res;
}
//前序-递归版本
void dfs(TreeNode* root, vector<int> &res) {
res.push_back(root->val);
if (root->left) {
dfs(root->left, res);
}
if (root->right) {
dfs(root->right, res);
}
}
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> res;
if (root == NULL) {
return res;
}
dfs(root, res);
return res;
}
//中序-非递归版本
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
while(root || !st.empty()) {
if (root) {
//只保留,不进行处理
st.push(root);
root = root->left;
} else {
//从最左边开始处理
TreeNode* temp = st.top();
st.pop();
res.push_back(temp->val);
root = temp->right;
}
}
return res;
}
//中序-递归版本
void dfs(TreeNode* root, vector<int> &res) {
if (root->left) {
dfs(root->left, res);
}
res.push_back(root->val);
if (root->right) {
dfs(root->right, res);
}
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if (root == NULL) {
return res;
}
dfs(root, res);
return res;
}