zoukankan      html  css  js  c++  java
  • 树的层次遍历

    题目

    LeetCode102.二叉树的层序遍历

    代码

     1 class Solution {
     2 public:
     3     
     4     vector<vector<int>>ans;
     5     vector<vector<int>> levelOrder(TreeNode* root) {
     6         if(root == NULL ) return ans;
     7         queue<TreeNode*>q;
     8         q.push(root);
     9         while(!q.empty()){
    10             int sum = q.size();
    11             vector<int>path;
    12             for(int i = 0;i < sum;i++){ //控制当前层全部弹出
    13                 auto t = q.front();path.push_back(t->val);
    14                 q.pop();
    15                 if(t->left!=NULL) {q.push(t->left);}
    16                 if(t->right!=NULL) {q.push(t->right);}
    17             }
    18             ans.push_back(path); 
    19         } 
    20         return ans;
    21     }
    22 };

    题目

    LeetCode199. 二叉树的右视图

    代码

     1 class Solution {
     2 public:
     3     vector<int>ans;
     4     vector<int> rightSideView(TreeNode* root) {
     5         if(root==NULL) return ans;
     6         queue<TreeNode*>q;
     7         q.push(root);
     8         while(!q.empty()){
     9             int sum = q.size();
    10             TreeNode* t;
    11             for(int i = 0;i < sum;i++){
    12                 t = q.front();q.pop();
    13                 if(t->left!=NULL) q.push(t->left);
    14                 if(t->right!=NULL) q.push(t->right);
    15             }
    16             ans.push_back(t->val);
    17         }
    18         return ans;
    19     }
    20 };

    题目

    LeetCode429. N 叉树的层序遍历

    代码

     1 class Solution {
     2 public:
     3     vector<vector<int>>ans;
     4     vector<vector<int>> levelOrder(Node* root) {
     5         if(root == NULL) return ans;
     6         queue<Node*>q;
     7         q.push(root);
     8         while(!q.empty()){
     9             int sum = q.size();
    10             vector<int>path;
    11             for(int i = 0;i < sum;i++){
    12                 auto t = q.front();q.pop();path.push_back(t->val);
    13                 for(int i = 0;i < t->children.size();i++){
    14                     if(t->children[i] != NULL) q.push(t->children[i]);
    15                 }
    16             }
    17             ans.push_back(path);
    18         }
    19         return ans;
    20     }
    21 };
  • 相关阅读:
    POJ2983Is the Information Reliable
    POJ2706Connect
    POJ1716Integer Intervals
    js Number 转为 百分比
    c# Unicode编码
    json datatable
    分割js 数组
    IQueryable定义一个扩展方法。分页
    sql 计算岁数
    sql 获取一个周的周一和周日
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14443788.html
Copyright © 2011-2022 走看看