[LeetCode]Binary Tree Level Order Traversal

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.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / 
 2   3
    /
   4
    
     5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

思考:BFS。num记录上一层有几个结点。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
	vector<vector<int> > ret;
public:
	vector<vector<int> > levelOrder(TreeNode *root) {
		// IMPORTANT: Please reset any member data you declared, as
		// the same Solution instance will be reused for each test case.
		ret.clear();
		if(root==NULL) return ret;
		vector<int> ans;
		queue<TreeNode *> q;	
		q.push(root);
		int num=1;
		while(!q.empty())
		{
			ans.clear();
			int count=0;
			while(num--)
			{			
				TreeNode *node=q.front();
				q.pop();
				ans.push_back(node->val);
				if(node->left)
				{
					count++;
					q.push(node->left);
				}
				if(node->right)
				{
					count++;
					q.push(node->right);
				}
			}
			num=count;
			if(ans.size()!=0)
			{
				ret.push_back(ans);
			}
		}
		return ret;
	}
};

  

原文地址:https://www.cnblogs.com/Rosanna/p/3429367.html