首页 > 其他 > 详细

Binary Tree Level Order Traversal

时间:2014-03-08 23:53:12      阅读:571      评论:0      收藏:0      [点我收藏+]

Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   /   9  20
    /     15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

许久未练, 生疏不少. 叹~

/**
 * Definition for binary tree
 * 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<int> vee;
        vector<vector<int>>ve;
        queue<TreeNode*> qu;
        TreeNode *no;
        if(NULL==root)
            return ve;
        qu.push(root);
        int len = qu.size();
        while(len!=0)
        {
            while(len--)
            {
                no = qu.front();
                qu.pop();
                vee.push_back(no->val);
                if(NULL!=no->left)qu.push(no->left);
                if(NULL!=no->right)qu.push(no->right);
            }
            ve.push_back(vee);
            vee.clear();
            len = qu.size();
        }
        return ve;
    }
};


Binary Tree Level Order Traversal,布布扣,bubuko.com

Binary Tree Level Order Traversal

原文:http://blog.csdn.net/vintionnee/article/details/20793455

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!