首页 > 代码库 > LeetCode[Tree]: Binary Tree Level Order Traversal

LeetCode[Tree]: Binary Tree Level Order Traversal

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

这个题目比较简单,借助容器queue即可完成二叉树的层序遍历。我的C++实现代码如下:

vector<vector<int> > levelOrder(TreeNode *root) {
    vector<vector<int> > result;
    vector<int> level;

    queue<TreeNode *> levelQ;
    if (root) levelQ.push(root);        
    while (!levelQ.empty()) {
        level.clear();
        int size = levelQ.size();
        for (int i = 0; i < size; ++i) {
            TreeNode *node = levelQ.front();
            levelQ.pop();

            level.push_back(node->val);

            if (node->left ) levelQ.push(node->left );
            if (node->right) levelQ.push(node->right);
        }

        result.push_back(level);
    }

    return result;
}


LeetCode[Tree]: Binary Tree Level Order Traversal