3.Binary Tree Level Order Traversal

https://leetcode.com/problems/binary-tree-level-order-traversal/

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

你可能感兴趣的:(3.Binary Tree Level Order Traversal)