美文网首页
102. Binary Tree Level Order Tra

102. Binary Tree Level Order Tra

作者: a_void | 来源:发表于2016-09-21 15:19 被阅读0次

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]
]

Solution:

/**
 * 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> > r = vector<vector<int> >();
        if(NULL == root) return r;
        
        deque<TreeNode*> d = deque<TreeNode*>();
        d.push_back(root);
        while(!d.empty()){
            int s = d.size();
            vector<int> v = vector<int>();
            v.reserve(s);
            for(int i=0;i<s;i++){
                TreeNode* p = d.front();
                d.pop_front();
                v.push_back(p->val);
                if(NULL != p->left) d.push_back(p->left);
                if(NULL != p->right) d.push_back(p->right);
            }
            r.push_back(v);
        }
        return r;
    }
};

相关文章

网友评论

      本文标题:102. Binary Tree Level Order Tra

      本文链接:https://www.haomeiwen.com/subject/deeaettx.html