即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

[BFS]102. Binary Tree Level Order Traversal

编程语言 Rewind_L 21℃ 0评论
题目:

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]
]

题目分析

这道题目就是107题的简化版,省略了倒叙的步骤,具体的解法参见107分析。此处只挂代码嘻嘻嘻


代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector> levelOrder(TreeNode* root) {
        vector> res;

        
        queue Q;
        Q.push(root);
        int th = 1;
        int ne = 0;
        
        if(root == NULL){
         return res;
        }
        
        while(!Q.empty()){
         vector put;
         for(int i = 0; i< th; i++){
          TreeNode* node = Q.front();
          put.push_back(node->val);
          if(node->left != NULL){
           Q.push(node->left);
           ne++;
          }
          if(node->right != NULL){
           Q.push(node->right);
           ne++;
          }
          Q.pop();
         }
         res.push_back(put);
         th = ne;
         ne = 0;
        }
        
        return res;
    }
};


转载请注明:CodingBlog » [BFS]102. Binary Tree Level Order Traversal

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情