Fork me on GitHub

102. Binary Tree Level Order Traversal

102. 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}". 

解析

// 102. Binary Tree Level Order Traversal
class Solution {
public:
	vector<vector<int> > levelOrder(TreeNode *root) {

		vector<vector<int>> vecs;

		if (!root)
		{
			return vecs;
		}
		queue<TreeNode*> que;
		que.push(root);

		while (!que.empty())
		{
			int size = que.size();
			vector<int> vec;

			while (size--)
			{
				TreeNode* temp = que.front();
				que.pop();

				vec.push_back(temp->val);
				if (temp->left)
				{
					que.push(temp->left);
				}
				if (temp->right)
				{
					que.push(temp->right);
				}
			}
			vecs.push_back(vec);
		}

		return vecs;
	}

	vector<vector<int>> levelOrder(TreeNode* root) {
		if (!root) { return{}; }
		vector<int> row;
		vector<vector<int> > result;
		queue<TreeNode*> q;
		q.push(root);
		int count = 1;

		while (!q.empty()) {
			if (q.front()->left) { q.push(q.front()->left); }
			if (q.front()->right) { q.push(q.front()->right); }
			row.push_back(q.front()->val), q.pop();
			if (--count == 0) {
				result.emplace_back(row), row.clear();
				count = q.size();
			}
		}
		return result;
	}

	// 递归实现;up->bottom
        //类似的:bottom->up: 107. Binary Tree Level Order Traversal II: http://www.cnblogs.com/ranjiewen/p/8253217.html

	vector<vector<int>> ret;
	void buildVector(TreeNode *root, int depth)
	{
		if (root == NULL) return;
		if (ret.size() == depth)
			ret.push_back(vector<int>());

		ret[depth].push_back(root->val);
		buildVector(root->left, depth + 1);
		buildVector(root->right, depth + 1);
	}

	vector<vector<int> > levelOrder(TreeNode *root) {
		buildVector(root, 0);
		return ret;
	}
};


题目来源

posted @ 2018-01-11 10:02  ranjiewen  阅读(362)  评论(0编辑  收藏  举报