其他分享
首页 > 其他分享> > 19.3.4 [LeetCode 102] Binary Tree Level Order Traversal

19.3.4 [LeetCode 102] 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,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

 

标签:Binary,20,19.3,Level,15,ans,push,return,now
来源: https://www.cnblogs.com/yalphait/p/10473864.html