标签:des style blog color io ar for sp div
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的应用,但是这里稍微复杂一点的是,我们要把各个层的数分开,存到一个二维向量里面,大体思路还是基本相同的,建立一个queue,然后先把根节点放进去,这时候找根节点的左右两个子节点,这时候去掉根节点,此时queue里的元素就是下一层的所有节点,用一个for循环遍历它们,然后存到一个一维向量里,遍历完之后再把这个一维向量存到二维向量里,以此类推,可以完成层序遍历。代码如下:
/** * Definition for binary tree * 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> > res; if (root == NULL) return res; queue<TreeNode*> q; q.push(root); while (!q.empty()) { vector<int> oneLevel; int size = q.size(); for (int i = 0; i < size; ++i) { TreeNode *node = q.front(); q.pop(); oneLevel.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } res.push_back(oneLevel); } return res; } };
Binary Tree Level Order Traversal 二叉树层序遍历
标签:des style blog color io ar for sp div
原文地址:http://www.cnblogs.com/grandyang/p/4051321.html