标签:des style color io os ar for 数据 sp
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?
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: std::vector<std::vector<int> > levelOrder(TreeNode *root){ //第一种解法,利用队列BFS分层遍历二叉树 std::vector<std::vector<int>> vec; if(root == NULL) return vec; std::queue<TreeNode*> Q; Q.push(root); int cnt = 1; std::vector<int> tmp; while(!Q.empty()) { tmp.clear(); int level = 0; for(int i = 0; i < cnt; i++) { root = Q.front(); Q.pop(); tmp.push_back(root->val); if(root->left != NULL) Q.push(root->left),level++; if(root->right != NULL) Q.push(root->right),level++; } cnt = level; vec.push_back(tmp); } return vec; } };
class Solution { public: std::vector<std::vector<int> > levelOrder(TreeNode *root){ //第二种方法也是利用队列的方法来做的,但是,其实数据结构的实现是vector,觉得这种方法更简便一些. std::vector<std::vector<int>> result; if(root == NULL) return result; std::vector<int> vec; std::vector<TreeNode*> node; node.push_back(root); int cur = 0,last = 1; while(cur < node.size()) { last = node.size(); while(cur < last) { vec.push_back(node[cur]->val); if(node[cur]->left != NULL) node.push_back(node[cur]->left); if(node[cur]->right != NULL) node.push_back(node[cur]->right); cur++; } result.push_back(vec); vec.clear(); } return result; } };
class Solution { public: std::vector<std::vector<int> > levelOrder(TreeNode *root){ //第三种解法,dfs分层遍历二叉树 dfs(root,0); return result; } private: std::vector<std::vector<int>> result; void dfs(TreeNode *root,int level) { if(root == NULL) return; if(level == result.size()) { std::vector<int> vec; result.push_back(vec); } result[level].push_back(root->val); dfs(root->left,level+1); dfs(root->right,level+1); } };
leetcode - Binary Tree Level Order Traversal
标签:des style color io os ar for 数据 sp
原文地址:http://blog.csdn.net/akibatakuya/article/details/39672355