[Leetcode] Binary Tree Level Order Traversal

Binary Tree Level Order Traversal Sep 29 '12 5832 / 14746

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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

 

return its level order traversal as:

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

 

/**
 * Definition for binary tree
 * 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;
        queue<TreeNode*> q;
        int cur = 1, next = 0;
        q.push(root);
        vector<int> a;
        while (!q.empty()) {
            auto tmp = q.front();
            q.pop();
            
            a.push_back(tmp->val);
            cur--;
            if (tmp->left != NULL) q.push(tmp->left), next++;
            
            if (tmp->right != NULL) q.push(tmp->right), next++;
            if (cur == 0) {
                cur = next;
                next = 0;
                res.push_back(a);
                a.clear();
            }
        }
        //if (a.size() > 0) res.push_back(a);
        return res;
    }
};

 

你可能感兴趣的:(LeetCode)