1. 程式人生 > >19.3.4 [LeetCode 102] Binary Tree Level Order Traversal

19.3.4 [LeetCode 102] Binary Tree Level Order Traversal

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 {
2 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 };
View Code

19.3.4 [LeetCode 102] Binary Tree Level Order Traversal