首页 > 其他 > 详细

LeetCode:Binary Tree Level Order Traversal

时间:2016-05-30 15:22:01      阅读:108      评论:0      收藏:0      [点我收藏+]

Binary Tree Level Order Traversal




Total Accepted: 105297 Total Submissions: 318601 Difficulty: Easy

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.

Subscribe to see which companies asked this question

































c++ code:

/**
 * 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>> ret;
        if(NULL == root) return ret;
        queue<TreeNode *> q[2];
        stack<vector<int>> s;
        int cur=0;
        q[cur].push(root);
        while(!q[cur].empty()) {
            vector<int> tmp;
            while(!q[cur].empty()) {
                TreeNode *p = q[cur].front();
                tmp.push_back(p->val);
                if(p->left) q[cur^1].push(p->left);
                if(p->right) q[cur^1].push(p->right);
                q[cur].pop();
            }
            cur^=1;
            ret.push_back(tmp);
        }
        return ret;
    }
};


LeetCode:Binary Tree Level Order Traversal

原文:http://blog.csdn.net/itismelzp/article/details/51524351

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