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

(leetcode)Binary Tree Level Order Traversal

时间:2015-09-24 15:59:45      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

Binary Tree Level Order Traversal

My Submissions
Total Accepted: 67360 Total Submissions: 228717 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.

 

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> levelOrder(TreeNode* root) {
13         queue<TreeNode*> que;
14         vector<vector<int>> ret;
15         if(!root) return ret;
16         int cur,next;
17         que.push(root);
18         cur = 1;next = 0;
19         vector<int> tmp;
20         while(!que.empty())
21         {
22             TreeNode* tmpNode;
23             tmpNode = que.front();
24             tmp.push_back(tmpNode->val);
25             que.pop();
26             cur--;
27             if(tmpNode->left) { que.push(tmpNode->left); next++; }
28             if(tmpNode->right) { que.push(tmpNode->right); next++; }
29             if(cur == 0) { cur = next; next = 0; ret.push_back(tmp); tmp.clear(); }
30             
31         }
32         
33         return ret;
34     }
35 };

 

(leetcode)Binary Tree Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/chdxiaoming/p/4835307.html

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