102.Binary Tree Level Order Traversal

思路:
  • 递归,利用level表示第几层。
/**
 * 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>>res;
        bfs(root,1,res);
        return res;
    }
    void bfs(TreeNode* root,int level,vector<vector<int>>& res){
        if(root == NULL) return ;
        vector<int> tmp;
        if(level > res.size()) res.push_back(tmp);
        res[level-1].push_back(root->val);      //注意,这里level不能替换成res.size()-1,调试了好久。。。
        bfs(root->left,level+1,res);
        bfs(root->right,level+1,res);
        
    }
};
  • 迭代,利用队列,一层一层进行遍历。
/**
 * 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) {
        if(root == NULL) return {};
        vector<vector<int>> res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int size = q.size();
            vector<int> level;
            for(int i = 0; i < size; i++){
                TreeNode *tmp = q.front();
                level.push_back(tmp->val);
                q.pop();
                if(tmp->left) q.push(tmp->left);
                if(tmp->right) q.push(tmp->right);
            }
            res.push_back(level);
        }
        return res;
    }
};
posted @ 2017-06-15 16:34  UniMilky  阅读(97)  评论(0编辑  收藏  举报