leetCode——二叉树的层次遍历

题目:https://leetcode-cn.com/explore/learn/card/data-structure-binary-tree/2/traverse-a-tree/9/

class Solution {
public:
    vector> levelOrder(TreeNode* root) { 
        vector> ans;
        if(!root) return ans;
        queue q;
        q.push(root);
        TreeNode* tr;
        while(!q.empty()){
            int n = q.size();
            vector v;
            for(int i = 0;ival);
                q.pop();
                if(tr->left) q.push(tr->left);
                if(tr->right) q.push(tr->right);
            }
            ans.push_back(v);
        }
        return ans;
    }
};

 

你可能感兴趣的:(刷LeetCode,leetcode,二叉树)