LeetCode:Binary Tree Level Order Traversal I II
LeetCode:Binary Tree Level Order Traversal
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]
] 本文地址
队列辅助层序遍历,队列中插入NULL作为层与层之间的间隔,注意处理队列里最后的NULL时,不能再把它入队列以免形成死循环
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> >res; 16 if(root == NULL)return res; 17 queue<TreeNode*> myqueue; 18 myqueue.push(root); 19 myqueue.push(NULL);//NULL是层与层之间间隔标志 20 vector<int> level; 21 while(myqueue.empty() == false) 22 { 23 TreeNode *p = myqueue.front(); 24 myqueue.pop(); 25 if(p != NULL) 26 { 27 level.push_back(p->val); 28 if(p->left)myqueue.push(p->left); 29 if(p->right)myqueue.push(p->right); 30 } 31 else 32 { 33 res.push_back(level); 34 if(myqueue.empty() == false) 35 { 36 level.clear(); 37 myqueue.push(NULL); 38 } 39 } 40 } 41 return res; 42 } 43 };
LeetCode:Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7] [9,20], [3], ]
和上一题差不多,只是需要把最后遍历结果数组翻转一下
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> > levelOrderBottom(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> >res; 16 if(root == NULL)return res; 17 queue<TreeNode*> myqueue; 18 myqueue.push(root); 19 myqueue.push(NULL);//NULL是层与层之间间隔标志 20 vector<int> level; 21 while(myqueue.empty() == false) 22 { 23 TreeNode *p = myqueue.front(); 24 myqueue.pop(); 25 if(p != NULL) 26 { 27 level.push_back(p->val); 28 if(p->left)myqueue.push(p->left); 29 if(p->right)myqueue.push(p->right); 30 } 31 else 32 { 33 res.push_back(level); 34 if(myqueue.empty() == false) 35 { 36 level.clear(); 37 myqueue.push(NULL); 38 } 39 } 40 } 41 reverse(res.begin(), res.end()); 42 return res; 43 } 44 };
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3440542.html