Leetcode 102. Binary Tree Level Order Traversal

 

 

二叉树的层序遍历,直接进行用二维vector进行层序,用一个queue进行,记录大小后,进行不断push进去。

/**
 * 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>> ans;
        if(!root) return ans;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()) {
            vector<int> tmp;
            int len = q.size();
            while(len--) {
                TreeNode* t = q.front();
                q.pop();
                tmp.push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
            ans.push_back(tmp);
        }
        return ans;
    }
};

 

posted @ 2020-02-07 03:12  SteveYu  阅读(111)  评论(0编辑  收藏  举报