LeetCode-Binary Tree Level Order Traversal-解题报告

原创 2015年07月08日 19:34:16

原题链接 https://leetcode.com/problems/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]
]

二叉树的层序遍历。使用BFS即可,或者使用迭代dfs也可以,可能会比较慢。


/**
 * 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> >ans;
		queue<TreeNode*>Q;
		vector<int>tmp;
		if (root == NULL)return ans;
		Q.push(root);
		while (!Q.empty())
		{
			tmp.clear();
			int size = Q.size();
			for (int i = 0; i < size; ++i)
			{
				TreeNode* t = Q.front();
				Q.pop();
				tmp.push_back(t->val);
				if (t->left != NULL)Q.push(t->left);
				if (t->right != NULL)Q.push(t->right);
			}
			ans.push_back(tmp);
		}
		return ans;
	}
};




相关文章推荐

【LeetCode】103. Binary Tree Zigzag Level Order Traversal 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280Subject 出处:https://leetcode.com/pro...

[Leetcode] 103. Binary Tree Zigzag Level Order Traversal 解题报告

题目: Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, fro...

Leetcode 103. Binary Tree Zigzag Level Order Traversal 二叉树Zigzag遍历 解题报告

1 解题思想首先这道题和 Leetcode 102. Binary Tree Level Order Traversal 二叉树按层遍历 解题报告 很接近,Zigzag同样是按层遍历,但是区别是对...
  • MebiuW
  • MebiuW
  • 2016年09月09日 12:26
  • 786

【LeetCode】Binary Tree Level Order Traversal II 解题报告

Binary Tree Level Order Traversal II [LeetCode] Given a binary tree, return the bottom-up level orde...

【LeetCode】102. Binary Tree Level Order Traversal 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51477967Subject 出处:https://leetcode.com/pro...

[leetcode]102. Binary Tree Level Order Traversal@Java解题报告

https://leetcode.com/problems/binary-tree-level-order-traversal/description/ Given a bina...

【LeetCode】Binary Tree Level Order Traversal 解题报告

Binary Tree Level Order Traversal [LeetCode] Given a binary tree, return the level order traversal o...

[leetcode]107. Binary Tree Level Order Traversal II@Java解题报告

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/ Given a b...

LeetCode 102. Binary Tree Level Order Traversal 解题报告

LeetCode 102. Binary Tree Level Order Traversal 解题报告题目描述Given a binary tree, return the level order ...

[leetcode]103. Binary Tree Zigzag Level Order Traversal@Java解题报告

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/ Given...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode-Binary Tree Level Order Traversal-解题报告
举报原因:
原因补充:

(最多只允许输入30个字)