102. Binary Tree Level Order Traversal

Posted mengchunchen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]
]

层次遍历

C++:
 1 /**
 2  * Definition for a binary tree node.
 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         if (root == NULL)
14             return vector<vector<int>>() ;
15         vector<vector<int>> res ;
16         vector<int> level ;
17         queue<TreeNode*> q ;
18         q.push(root) ;
19         while(!q.empty()){
20             int len = q.size() ;
21             for(int i = 0 ; i < len ; i++){
22                 TreeNode* temp = q.front() ;
23                 q.pop() ;
24                 if (temp->left != NULL)
25                     q.push(temp->left) ;
26                 if (temp->right != NULL)
27                     q.push(temp->right) ;
28                 level.push_back(temp->val) ;
29             }
30             res.push_back(level) ;
31             level.clear() ;
32         }
33         return res;
34     }
35 };

 

 






以上是关于102. Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

102. Binary Tree Level Order Traversal

LeetCode102. Binary Tree Level Order Traversal

102Binary Tree Level Order Traversal

102. Binary Tree Level Order Traversal

Leetcode 102. Binary Tree Level Order Traversal

[LeetCode]题解(python):102 Binary Tree Level Order Traversal