力扣精选top面试题-------- 二叉树的遍历

在这里插入图片描述
题目链接

思路:
这道题其实是模板题,必须好好掌握二叉树的遍历方式,我这边了解到的共有三种:递归,非递归,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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43743711/article/details/114007282
今日推荐