69 二叉树的层次遍历
原题网址:http://www.lintcode.com/problem/binary-tree-level-order-traversal/
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
您在真实的面试中是否遇到过这个题?
Yes
样例
给一棵二叉树 {3,9,20,#,#,15,7}
:
3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
挑战
挑战1:只使用一个队列去实现它
挑战2:用DFS算法来做
标签
非挑战AC代码:
思路是,用两个数组分别保存上一层的节点与当前层节点。
上一层节点不为空时,依次访问,并将其左右孩子添加到当前层节点数组。上一层数组访问完毕,将当前层数组赋给上一层数组,继续循环。
这里试了下,将v2赋值给v1是可以直接使用“=”符号的……
1 /** 2 * Definition of TreeNode: 3 * class TreeNode { 4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * TreeNode(int val) { 8 * this->val = val; 9 * this->left = this->right = NULL; 10 * } 11 * } 12 */ 13 14 class Solution { 15 public: 16 /** 17 * @param root: A Tree 18 * @return: Level order a list of lists of integer 19 */ 20 vector<vector<int>> levelOrder(TreeNode * root) { 21 // write your code here 22 vector<vector<int>> result; 23 if (root==NULL) 24 { 25 return result; 26 } 27 28 vector<TreeNode *> preLevelNode; 29 preLevelNode.push_back(root); 30 31 while(!preLevelNode.empty()) 32 { 33 vector<TreeNode *> curLevelNode; 34 vector<int> temp; 35 for (int i=0;i<(int)preLevelNode.size();i++) 36 { 37 TreeNode *p=preLevelNode[i]; 38 temp.push_back(p->val); 39 if (p->left!=NULL) 40 { 41 curLevelNode.push_back(p->left); 42 } 43 if (p->right!=NULL) 44 { 45 curLevelNode.push_back(p->right); 46 } 47 } 48 result.push_back(temp); 49 //preLevelNode.clear(); 50 //preLevelNode=curLevelNode; 51 preLevelNode.assign(curLevelNode.begin(),curLevelNode.end()); 52 } 53 54 return result; 55 } 56 };
挑战1:只使用一个队列去实现它
参考:https://blog.csdn.net/ljlstart/article/details/48502759
1 /** 2 * Definition of TreeNode: 3 * class TreeNode { 4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * TreeNode(int val) { 8 * this->val = val; 9 * this->left = this->right = NULL; 10 * } 11 * } 12 */ 13 14 class Solution { 15 public: 16 /** 17 * @param root: A Tree 18 * @return: Level order a list of lists of integer 19 */ 20 vector<vector<int>> levelOrder(TreeNode * root) { 21 // write your code here 22 vector<vector<int>> result; 23 if (root==NULL) 24 { 25 return result; 26 } 27 queue<TreeNode *> level; 28 level.push(root); 29 int len; //计数器,记录每层节点数量; 30 31 while(!level.empty()) 32 { 33 len=level.size(); 34 vector<int> temp; 35 while(len--) //遍历当前层数值,并将当前层节点的左右孩子入队列; 36 { 37 TreeNode *p=level.front(); 38 level.pop(); 39 temp.push_back(p->val); 40 if (p->left!=NULL) 41 { 42 level.push(p->left); 43 } 44 if (p->right!=NULL) 45 { 46 level.push(p->right); 47 } 48 } 49 result.push_back(temp); 50 } 51 return result; 52 } 53 };