19.3.4 [LeetCode 102] Binary Tree Level Order Traversal
阿新 • • 發佈:2019-03-05
level tco one 技術分享 () clas oot rsa example
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,null,null,15,7]
,
3
/ 9 20
/ 15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
1 class Solution {View Code2 public: 3 vector<vector<int>> levelOrder(TreeNode* root) { 4 queue<TreeNode*>q, p; 5 vector<vector<int>>ans; 6 if(!root)return ans; 7 int i = 0; 8 q.push(root); 9 while (!q.empty()) { 10 ans.push_back(vector<int>()); 11 while (!q.empty()) { 12 TreeNode*now = q.front(); q.pop(); 13 ans[i].push_back(now->val); 14 if (now->left) 15 p.push(now->left); 16 if (now->right) 17 p.push(now->right);18 } 19 q = p; 20 p = queue<TreeNode*>(); 21 i++; 22 } 23 return ans; 24 } 25 };
19.3.4 [LeetCode 102] Binary Tree Level Order Traversal