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 7return its level order traversal as:
[ [3], [9,20], [15,7] ]
这道题目是二叉树的层次遍历。
思路:借助于队列结构(queue),保存尚未访问儿子节点的节点。
这道题一大注意点在于,每层结束后插入NULL作为分隔符。
1. 初始化:将根节点和第一层终止符NULL压入队列
2. 循环
用level记录该层的节点val
- 取出队首元素cur
- 若cur非空, 记录cur->val
若cur为NULL,则说明该层节点已全部访问过,将level插入ret.
若此时queue非空,访问下一层节点,否则,停止循环
代码
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> levelOrder(TreeNode *root) { 13 // IMPORTANT: Please reset any member data you declared, as 14 // the same Solution instance will be reused for each test case. 15 vector<vector<int>> ret; 16 if(root==NULL) 17 return ret; 18 19 queue<TreeNode *> q; 20 q.push(root); 21 q.push(NULL); // IMPORTANT! end of level 22 23 vector<int> level; 24 25 while(!q.empty()) 26 { 27 TreeNode *cur = q.front(); 28 q.pop(); 29 30 if(cur) 31 { 32 level.push_back(cur->val); 33 if(cur->left) 34 q.push(cur->left); 35 if(cur->right) 36 q.push(cur->right); 37 } 38 else 39 { 40 ret.push_back(level); 41 level.clear(); 42 if(q.empty()) 43 break; 44 else 45 q.push(NULL); 46 } 47 } 48 return ret; 49 } 50 };