Idea: This
question is actually a template question. You must master the traversal method of the binary tree. There are three kinds of knowledge I have learned here: recursion, non-recursion, and Morries algorithm. I will summarize these knowledge later, and now I will use the recursive algorithm. To solve it.
Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> q;
void func(TreeNode* root){
if(root==NULL) return ;
func(root->left);
q.push_back(root->val);
func(root->right);
}
vector<int> inorderTraversal(TreeNode* root) {
func(root);
return q;
}
};
//非递归版本 中序和先序的代码是一样的,只不过打印节点的值位置不一样而已,后序比较麻烦
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> q;
stack<TreeNode*> st;
while( !(st.size()==0 && root==NULL) ){
if(root!=NULL){
st.push(root);
root = root->left;
}else{
auto it = st.top();
st.pop();
q.push_back(it->val);
root = it->right;
}
}
return q;
}
};
//非递归后序遍历
//明确只有两种情况:一是没有右节点,二是prev(上一次访问打印的点)是该节点的右节点
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
if (root == nullptr) {
return res;
}
stack<TreeNode *> stk;
TreeNode *prev = nullptr;
while (root != nullptr || !stk.empty()) {
if(root!=NULL){
stk.push(root);
root=root->left;
}else{
root = stk.top();
if(root->right==nullptr || root->right==prev){
res.push_back(root->val);
stk.pop();
prev = root;
root = nullptr;
}else{
root=root->right;
}
}
}
return res;
}
};