代码随想录训练营Day10 | 二叉树的遍历

递归遍历

c++ 复制代码
   void preRecur(vector<int>& ans, TreeNode* root) {
        if(root) {
            ans.push_back(root->val);
            preRecur(ans, root->left);
            preRecur(ans, root->right);
        }
    }
  1. 145.二叉树的后序遍历
c++ 复制代码
 void sufRecur(vector<int>& ans, TreeNode* root) {
        if(root) {
            sufRecur(ans, root->left);
            sufRecur(ans, root->right);
            ans.push_back(root->val);
        }
    }
  1. 94.二叉树的中序遍历
c++ 复制代码
 void inRecur(vector<int>& ans, TreeNode* root) {
        if(root) {
            inRecur(ans, root->left);
            ans.push_back(root->val);
            inRecur(ans, root->right);
          
        }
    }

层序遍历

c++ 复制代码
void preIter(vector<int>& ans, TreeNode* root) {
        stack<TreeNode*> s;
        s.push(root);
        while(!s.empty()) {
            TreeNode* t = s.top();
            ans.push_back(t->val);
            s.pop();

            if(t->right)
                s.push(t->right);
            if(t->left)
                s.push(t->left);
        }
    }
  1. 145.二叉树的后序遍历
c++ 复制代码
 void sufIter(vector<int>& ans, TreeNode* root) {
        stack<TreeNode*> s;
        TreeNode* cur = root;
        TreeNode* prev = nullptr;
        while(cur || !s.empty()) {
            while(cur) {
                s.push(cur);
                cur = cur->left;
            }
            cur = s.top();
            s.pop();
            if(cur->right == nullptr || cur->right == prev) {
                ans.push_back(cur->val);
                prev = cur;
                cur = nullptr;
            } else {
                s.push(cur);
                cur = cur->right;
            }
        }
    }
  1. 94.二叉树的中序遍历
c++ 复制代码
  void inIter(vector<int>& ans, TreeNode* root) {
        stack<TreeNode*> s;
        TreeNode* cur = root;
        while(cur || !s.empty()) {
            while(cur) {
                s.push(cur);
                cur = cur->left;
            }

            cur = s.top();
            s.pop();
            ans.push_back(cur->val);
            cur = cur->right;
        }
    }

二叉树的层序遍历

c++ 复制代码
class Solution {
public:
    
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if(!root) return ans;
        TreeNode* cur = nullptr;
        deque<TreeNode*> dq;
        dq.push_back(root); // 双端队列
        while(!dq.empty()) {
            vector<int> t;
            int n = dq.size(); // 遍历一层
            for(int i = 0; i < n; ++i) {
                cur = dq.front();
                dq.pop_front();
                t.push_back(cur->val);
                if(cur->left)
                    dq.push_back(cur->left);
                if(cur->right)
                    dq.push_back(cur->right);
            }
            ans.push_back(t);
        }
        return ans;
    }
};

107.二叉树的层次遍历II

c++ 复制代码
class Solution {
public:
	// 思路与上题一致
    vector<vector<int>> levelOrderBottom(TreeNode *root) {
        if (root == nullptr) return {};
        vector<vector<int>> ans;
        vector<TreeNode*> cur{root};
        while (cur.size()) {
            vector<TreeNode*> nxt;
            vector<int> vals;
            for (auto node : cur) {
                vals.push_back(node->val);
                if (node->left)  nxt.push_back(node->left);
                if (node->right) nxt.push_back(node->right);
            }
            cur = move(nxt);
            ans.emplace_back(vals);
        }
        ranges::reverse(ans);
        return ans;
    }
};

199.二叉树的右视图

c++ 复制代码
class Solution {
    vector<int> ans;

    void dfs(TreeNode* node, int depth) {
        if (node == nullptr) {
            return;
        }
        if (depth == ans.size()) { // 这个深度首次遇到
            ans.push_back(node->val);
        }
        dfs(node->right, depth + 1); // 先递归右子树,保证首次遇到的一定是最右边的节点
        dfs(node->left, depth + 1);
    }

public:
    vector<int> rightSideView(TreeNode* root) {
        dfs(root, 0);
        return ans;
    }
};

637.二叉树的层平均值

c++ 复制代码
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> ans;
        if(!root) return ans;
        TreeNode* cur = nullptr;
        deque<TreeNode*> dq;
        dq.push_back(root);
        while(!dq.empty()) {
            int n = dq.size();
            double sum = 0;
            for(int i = 0; i < n; ++i) {
                cur = dq.front();
                dq.pop_front();
                sum += cur->val;                
                if(cur->left)
                    dq.push_back(cur->left);
                if(cur->right)
                    dq.push_back(cur->right);
            }
            ans.push_back(sum / n);
        }
        return ans;
    }
};

429.N叉树的层序遍历

c++ 复制代码
class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
         vector<vector<int>> ans;
        if(!root) return ans;
        Node* cur = nullptr;
        deque<Node*> dq;
        dq.push_back(root);
        while(!dq.empty()) {
            vector<int> t;
            int n = dq.size();
            for(int i = 0; i < n; ++i) {
                cur = dq.front();
                dq.pop_front();
                t.push_back(cur->val);
                for(Node* t : cur->children) 
                    dq.push_back(t);
            }
            ans.push_back(t);
        }
        return ans;
    }
};

515.在每个树行中找最大值

c++ 复制代码
class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        if (!root) {
            return {};
        }
        vector<int> res;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int len = q.size();
            int maxVal = INT_MIN;
            while (len > 0) {
                len--;
                auto t = q.front();
                q.pop();
                maxVal = max(maxVal, t->val);
                if (t->left)  q.push(t->left);
                if (t->right) q.push(t->right);
            }
            res.push_back(maxVal);
        }
        return res;
    }
};

116.填充每个节点的下一个右侧节点指针

c++ 复制代码
class Solution {
public:
    Node* connect(Node* root) {
        if(!root) return nullptr;
        Node* cur = nullptr;
        deque<Node*> dq;
        dq.push_back(root);
        while(!dq.empty()) {
            int n = dq.size();
            for(int i = 0; i < n; ++i) {
                cur = dq.front();
                dq.pop_front();
                if(i != n - 1)
                    cur->next = dq.front();  // 填充next
                if(cur->left) dq.push_back(cur->left);
                if(cur->right) dq.push_back(cur->right);
            }
        }
        return root;
    }
};

117.填充每个节点的下一个右侧节点指针II

c++ 复制代码
class Solution {
public:
    Node* connect(Node* root) {
        if(!root) return nullptr;
        Node* cur = nullptr;
        deque<Node*> dq;
        dq.push_back(root);
        while(!dq.empty()) {
            int n = dq.size();
            for(int i = 0; i < n; ++i) {
                cur = dq.front();
                dq.pop_front();
                if(i != n - 1)
                    cur->next = dq.front(); // 填充next
                if(cur->left) dq.push_back(cur->left);
                if(cur->right) dq.push_back(cur->right);
            }
        }
        return root;
    }
};

104.二叉树的最大深度

c++ 复制代码
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) {
            return 0;
        }
        int l_depth = maxDepth(root->left);
        int r_depth = maxDepth(root->right);
        return max(l_depth, r_depth) + 1; // 记录高度,记录高度最大值
    }
};

111.二叉树的最小深度

c++ 复制代码
class Solution {
    int ans = INT_MAX; // 遍历时记录高度,遍历到叶子节点取高度最小值
    void dfs(TreeNode *node, int cnt) {
        if (node == nullptr) {
            return;
        }
        cnt++;
        if (node->left == node->right) { // node 是叶子
            ans = min(ans, cnt);
            return;
        }
        dfs(node->left, cnt);
        dfs(node->right, cnt);
    };
public:
    int minDepth(TreeNode *root) {
        dfs(root, 0);
        return root ? ans : 0;
    }
};
相关推荐
闪电悠米11 小时前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
栋***t11 小时前
从“纸质试卷”到“AI智能组卷”,麦塔在线考试系统如何重构出题逻辑?
java·大数据·人工智能·算法·重构
wabs66611 小时前
关于图论【卡码网100.最大岛屿的面积的思考】
数据结构·算法·图论
CHANG_THE_WORLD11 小时前
深入理解递归:从函数调用到调用栈的完整执行过程
java·开发语言·算法
geovindu13 小时前
go:Backtracking Algorithm
开发语言·后端·算法·golang·回溯算法
微露清风13 小时前
模拟算法学习记录
学习·算法
KaMeidebaby13 小时前
卡梅德生物技术快报 | abcore 纳米抗体文库:从PNAS论文看纳米抗体理性设计:构象熵作为亲和力预测新指标的技术实现
java·开发语言·人工智能·算法·机器学习
问商十三载14 小时前
2026法律行业AI引擎生成式优化怎么优化?三层专业加固提排名,零成本提33%引用率附适配表
java·前端·人工智能·算法
zander25814 小时前
138. 随机链表的复制
数据结构·算法·链表