码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Level Order Traversal

时间:2015-07-28 17:50:24      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * 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>> vv;
        vector<int>v;
        if(root == NULL) return vv;
        int h0=1;
        int h1;
        TreeNode* temp;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            h1=0;
            while(h0--){
                temp=q.front();
                q.pop();
                v.push_back(temp->val);
                if(temp->left) {q.push(temp->left);h1++;}
                if(temp->right) {q.push(temp->right);h1++;}
            }
            vv.push_back(v);
            v.clear();
            h0=h1;
        }
        return vv;
    }
};

 

Binary Tree Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/julie-yang/p/4683264.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!