Un código 102. Recorrido de orden de nivel del árbol binario todos los días

inserte la descripción de la imagen aquí

La idea del código es
bfs, porque la jerarquía no se puede obtener por recorrido directo, por lo tanto, se redefine una estructura para registrar la altura del nodo actual.

Se tarda diez minutos en codificar y dos horas en depurar. La membresía de leetcode es realmente costosa. Todavía es una depuración manual de vscode. Un '!' bien escrito busqué durante una hora, y fui súper valiente. (╬◣д◢)

código

/**
 * 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:
    struct Node{
    
    
        TreeNode *ptr;
        int high;   //节点高度
    };
    vector<vector<int>> levelOrder(TreeNode* root) {
    
    
        //bfs遍历
        vector<vector<int> > v;
        if(!root) return v;         //这步不能丢,根结点如果是空节点,下面val入vector会报错
        vector<int> vv;
        queue<Node> q;
        q.push({
    
    root,0});
        int h_limit=0;
        while(!q.empty()){
    
          //节点全部处理
            Node tmp = q.front();
            q.pop();
            if(tmp.high != h_limit){
    
        //到达下一层,将上一层结果存入v,并清空vv
                v.push_back(vv);        //vector套vector只能push_back vector
                vv.clear();
                h_limit = tmp.high;
            }
            vv.push_back(tmp.ptr->val);
            if(tmp.ptr->left) q.push({
    
    tmp.ptr->left,tmp.high+1});   //左右孩子入队
            if(tmp.ptr->right) q.push({
    
    tmp.ptr->right,tmp.high+1});
        }
        v.push_back(vv);
        vv.clear();
        
        return v;
    }
};

Se adjunta un código de depuración.

#include<bits/stdc++.h>
//#include<stdio.h>
using namespace std;
typedef int ElemType;
const int maxn=105;


//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:
    struct Node{
    
    
        TreeNode *ptr;
        int high;
    };
    vector<vector<int>> levelOrder(TreeNode* root) {
    
    
        vector<vector<int> > v;
        vector<int> vv;
        queue<Node> q;
        q.push({
    
    root,0});
        int h_limit=0;
        while(!q.empty()){
    
    
            Node tmp = q.front();
            q.pop();
            if(tmp.high != h_limit){
    
    
                v.push_back(vv);
                vv.clear();
                h_limit = tmp.high;
            }
            vv.push_back(tmp.ptr->val);
            if(tmp.ptr->left) q.push({
    
    tmp.ptr->left,tmp.high+1});
            if(tmp.ptr->right) q.push({
    
    tmp.ptr->right,tmp.high+1});
        }
        v.push_back(vv);
        vv.clear();
        return v;
    }
};
int a[7];
TreeNode* build(TreeNode *root,int x){
    
    
    if(x >= 7 || a[x] == 0) root = NULL;
    else {
    
    
        TreeNode *node = new TreeNode(-1);
        node->val=a[x];
        node->left = node->right = NULL;
        root=node;
    }
    if(!root) return NULL;
    root->left = build(root->left,2*x+1);
    root->right = build(root->right,2*x+2);
    return root;
}

int main(){
    
    

#ifndef ONLINE_JUDGE
    // freopen("1.in","r",stdin);
    //freopen("1.out","w",stdout);
#endif  
    for(int i = 0; i < 7; ++i) cin>>a[i];
    // for(int i = 0; i < 7; ++i) cout<<a[i]<<" ";
    TreeNode *root = new TreeNode(-1);
    root = build(root,0);
    // cout<<root->left->val<<endl;
    vector<vector<int> > v;
    Solution s;
    v = s.levelOrder(root);
    for(int i = 0; i < v.size(); ++i){
    
    
        for(int j = 0; j < v[i].size(); ++j){
    
    
            cout<<v[i][j]<<" ";
        }
        cout<<endl;
    }
}

Supongo que te gusta

Origin blog.csdn.net/qq_41746268/article/details/108205150
Recomendado
Clasificación