`
cozilla
  • 浏览: 91873 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[Leetcode] Binary Tree Level Order Traversal

 
阅读更多
Binary Tree Level Order TraversalSep 29 '125832 / 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;
    }
};

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics