欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode—树—层次遍历

程序员文章站 2022-03-13 12:58:59
...

LeetCode—树—层次遍历

使用 BFS 进行层次遍历。不需要使用两个队列来分别存储当前层的节点和下一层的节点,因为在开始遍历一层的节点时,当前队列中的节点数就是当前层的节点数,只要控制遍历这么多节点数,就能保证这次遍历的都是当前层的节点。

1、一棵树每层节点的平均数
T637. Average of Levels in Binary Tree (Easy)
LeetCode—树—层次遍历

/**
 * 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<double> averageOfLevels(TreeNode* root) {
        if(!root)  return {};
        vector<double> res;
        queue<TreeNode*> q{{root}};
        while(!q.empty()){
            int n=q.size();
            double sum=0;
            for(int i=0; i<n; ++i){
                TreeNode* t = q.front();
                q.pop();
                sum += t->val;
                if(t->left)  q.push(t->left);
                if(t->right)  q.push(t->right);
            }
            res.push_back(sum/n);
        }
        return res;

    }
};

2、得到左下角的节点
T513. Find Bottom Left Tree Value (Easy)
LeetCode—树—层次遍历

/**
 * 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:
    int findBottomLeftValue(TreeNode* root) {
        int res=0;
        queue<TreeNode*> q{{root}};
        while(!q.empty()){
            int n=q.size();
            for(int i=0; i<n; ++i){
                TreeNode* t = q.front();
                q.pop();
                if(i == 0) res = t->val;
                if(t->left)  q.push(t->left);
                if(t->right)  q.push(t->right);
            }
        }
        return res;


    }
};