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

102. Binary Tree Level Order Tra

作者: juexin | 来源:发表于2017-01-07 13:54 被阅读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]]

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> arr;
        if(root==NULL)
          return arr;
        queue<TreeNode *> q;
        q.push(root);
        while(!q.empty())
        {
            int i = 0;
            int height = q.size();
            vector<int> c;
            while(i++<height)
            {
                TreeNode* t = q.front();
                q.pop();
                c.push_back(t->val);
                if(t->left)
                  q.push(t->left);
                if(t->right)
                  q.push(t->right);
            }
            arr.push_back(c);
        }
        return arr;
    }
};

相关文章

网友评论

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

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