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

原题链接 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;
	}
};




阅读更多
文章标签: C++ leetcode
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭