zoukankan      html  css  js  c++  java
  • 二叉树的层序遍历

      class Solution {
      public:
          vector<vector<int>> levelOrder(TreeNode* root) {
              vector<vector<int>> res;
              //注意判断根为空的情况
              if (root == NULL)   
                  return res;
              queue<TreeNode*> Q;
              Q.push(root);
              while (!Q.empty()) {
                  //保存每一层的结点
                  vector<int> ans;
                  //对队列中的同一层结点进行处理
                  int width = Q.size();    
                  for (int i = 0; i < width; i++) {
                      TreeNode* p = Q.front();
                      ans.push_back(p->val);
                      Q.pop();
                      if (p->left)
                          Q.push(p->left);
                      if (p->right)
                          Q.push(p->right);
                  }
                  res.push_back(ans);
              }
              return res;
          }
      };
    #include<iostream>
    #include<queue>
    #include<math.h>
    #include<algorithm>
    using namespace std;
    int a[100005];
    struct node {
        int val;
        node* left;
        node* right;
    }Treenode[1000];
    node* creat(int n) {
        //初始化数组
        for (int i = 1; i <= n; i++) {
            Treenode[i].left = nullptr;
            Treenode[i].right = nullptr;
            Treenode[i].val = i;
        }
        for (int i = 1; i <= n / 2; i++) {
            if(i*2<=n)
                Treenode[i].left = &Treenode[i * 2];
            if(i*2+1<=n)
                Treenode[i].right =&Treenode[i * 2 + 1];
        }
        return &Treenode[1];
    }
    void Print(node* root) {
        queue<node*>p;
        p.push(root);
        while (!p.empty()) {
            node* temp = p.front();
            p.pop();
            if (temp != nullptr) {
                cout << temp->val << endl;
                if(temp->left!=nullptr)
                    p.push(temp->left);
                if(temp->right!=nullptr)
                    p.push(temp->right);
            }
        }
    }
    int main()
    {
        node* root = creat(100);
        Print(root);
        return 0;
    }
  • 相关阅读:
    luogu P3375 【模板】KMP字符串匹配
    leetcode[129]Sum Root to Leaf Numbers
    leetcode[130]Surrounded Regions
    leetcode[131]Palindrome Partitioning
    leetcode[132]Palindrome Partitioning II
    leetcode[133]Clone Graph
    leetcode[134]Gas Station
    leetcode[135]Candy
    leetcode[136]Single Number
    leetcode[137]Single Number II
  • 原文地址:https://www.cnblogs.com/-citywall123/p/12892943.html
Copyright © 2011-2022 走看看