思路:
这道题其实是模板题,必须好好掌握二叉树的遍历方式,我这边了解到的共有三种:递归,非递归,Morries算法,这些知识后面我会总结起来,现在这里就用递归算法来解决。
代码:
/**
* 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;
}
};