Skip to content

二叉树分层

分层打印二叉树

一个不用显示记录节点层数,或者用两个队列轮换的小技巧:

/**
 * 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;
        vector<int> tmp;
        if (root == NULL) return ans;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            // must fix the current queue size ! `for (;i<q.size();)` is wrong.
            int s = q.size();
            for (int i = 0; i < s; i++) {
                TreeNode* p = q.front(); q.pop();
                tmp.push_back(p->val);
                if (p->left) q.push(p->left);
                if (p->right) q.push(p->right);
            }
            ans.push_back(tmp);
            tmp.clear();
        }
        return ans;        
    }
};