标签:leetcode tree 算法 层序遍历 queue
Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).
这个题目比较简单,借助容器queue即可完成二叉树的层序遍历。我的C++实现代码如下:
vector<vector<int> > levelOrder(TreeNode *root) { vector<vector<int> > result; vector<int> level; queue<TreeNode *> levelQ; if (root) levelQ.push(root); while (!levelQ.empty()) { level.clear(); int size = levelQ.size(); for (int i = 0; i < size; ++i) { TreeNode *node = levelQ.front(); levelQ.pop(); level.push_back(node->val); if (node->left ) levelQ.push(node->left ); if (node->right) levelQ.push(node->right); } result.push_back(level); } return result; }
LeetCode[Tree]: Binary Tree Level Order Traversal
标签:leetcode tree 算法 层序遍历 queue
原文地址:http://blog.csdn.net/chfe007/article/details/41556863