【LeetCode 】102. Binary Tree Level Order Traversal

来源:互联网 发布:匡威帆布鞋淘宝店代理 编辑:程序博客网 时间:2024/06/06 01:58

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

其实就是树的广度优先搜索,使用队列进行辅助,遍历每一层/** * 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<vector<int>> levelOrder(TreeNode* root) {        vector<vector<int>> res;         if (root == NULL) return res;        vector<int> sub;    // 存储每一层每个结点的值        queue<TreeNode *> q; // 辅助队列        q.push(root);        while (!q.empty()) { // q为空时结束循环            queue<TreeNode *> tmpq; // 临时队列,存储下一层的结点            while (!q.empty()) {                sub.push_back(q.front()->val);  // 将该层节点值加入sub中                if (q.front()->left != NULL) tmpq.push(q.front()->left); // 依次将左右子结点放入队列中                if (q.front()->right != NULL) tmpq.push(q.front()->right);                q.pop(); // 弹出一个结点,为空时表明当前层的所有结点都被遍历过            }            res.push_back(sub); // 加入结果集            q = tmpq;         // 更新队列            sub.clear();      // 清空,以备下次使用        }        return res;    }};
阅读全文
0 0