给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

解题思路:

广度优先搜索(BFS)。

Leetcode:102. 二叉树的层次遍历

C++代码
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if (root == NULL) return res;
        queue<TreeNode*> Q;
        TreeNode* node;
        vector<int> res1;
        Q.push(root);
        while (!Q.empty()) {
            int size = Q.size();
            res1.clear();
            for (int i = 1; i <= size; i++) {
                node = Q.front();
                res1.push_back(node->val);
                if (hasLChild(node)) { Q.push(node->left); }
                if (hasRChild(node)) { Q.push(node->right); }
                Q.pop();
            }
            res.push_back(res1);
        }
        return res;
    }
};

 

相关文章:

  • 2022-01-12
  • 2021-11-23
  • 2022-02-12
  • 2022-01-24
  • 2021-06-25
猜你喜欢
  • 2021-09-21
  • 2021-07-27
  • 2021-12-08
  • 2021-07-11
  • 2022-12-23
  • 2021-07-31
  • 2021-04-22
相关资源
相似解决方案