Bootstrap

二叉树的三种遍历 (递归+迭代)

前言:真的好久没有写博客了。最近也到春招季了,想必很多小伙伴在准备面试了,因此想着来写一篇关于二叉树遍历的博客。同时也希望大家:山水万程,皆有好运!


定义树结构:

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

递归版本:

  • 普通写法
void dfs(TreeNode *root){
    if(!root)
        return;
    // Preorder
    dfs(root->left);
    // Inorder
    dfs(root->right);
    // Postorder
}
  • C++的 Lambda 写法
void solve(TreeNode *root) {
    auto dfs = [&](auto self, TreeNode *rt) -> void{
       if(!root)
        	return;
        // Preorder
        self(self, rt->left);
        // Inorder
        self(self, rt->right);
        // Postorder
    };

    dfs(dfs, rt);
}

迭代版本:

  • 前序遍历
vector<int> preOrder(TreeNode *root) {
    vector<int> order;
    if(!root){
        return ;
    }
    
    stack<TreeNode *> s;
    s.push(root);
    
    while(s.size()){
        TreeNode *cur = s.top();
        s.pop();
        order.emplace_back(cur->val);
        
        if(cur->right){
            s.push(cur->right);
        }
        if(cur->left){
            s.push(cur->left);
        }
    }
    
    return order;
}
  • 中序遍历
vector<int> inOrder(TreeNode *root) {
    vector<int> order;
    if(!root)
        return order;
    
    unordered_set<TreeNode *> vis;
    stack<TreeNode *> s;
    
    s.push(root);
    while(s.size()){
        TreeNode *cur = s.top();
        if(vis.count(cur)){
            order.emplace_back(cur->val);
            s.pop();
            if(cur->right)
                s.push(cur->right);
        }else{
            vis.emplace(cur);
            if(cur->left)
                s.push(cur->left);
        }
    }
    
    return order;
}
  • 后序遍历
vector<int> postOrder(TreeNode *root) {
    vector<int> order;

    if(!root)
        return order;

    unordered_set<TreeNode *> vis;
    stack<TreeNode *> s;
    
    s.push(root);
    while(s.size()){
        TreeNode *cur = s.top();
        
        if((!cur->left and !cur->right) || vis.count(cur)){
            order.emplace_back(cur->val);
            s.pop();
        }else{
            vis.emplace(cur);
            if(cur->right)
                s.push(cur->right);
            if(cur->left)
                s.push(cur->left);
        }
    }
    return order;
}


以上就是这篇博客的全部内容,若内容有误,欢迎大家指出!

;