7-11 Layer 2 node statistics of binary search tree (C++)

A binary search tree is either an empty tree, or a binary tree with the following properties: if its left subtree is not empty, the values ​​of all nodes on the left subtree are less than or equal to the value of its root node; If its right subtree is not empty, the values ​​of all nodes on the right subtree are greater than the value of its root node; its left and right subtrees are also binary search trees.

Insert a series of numbers into an initially empty binary search tree in a given order, and your task is to count the number of nodes in the bottom 2 layers of the result tree.

Input format: Enter a positive integer N (≤1000) in the first line, which is the number of inserted numbers. The second line gives N integers in the interval [−1000,1000]. Numbers are separated by spaces.

Output format: output the total number of nodes in the bottom 2 layers in one line.

Input sample: 9
25 30 42 16 20 20 35 -5 28
Output sample: 6

code length limit

16 KB

time limit

400 ms

memory limit

64 MB

#include <bits/stdc++.h>
using namespace std;

typedef struct Node {
    int val;
    Node* left;
    Node* right;
    int size; //子树数量
    int tall;//高度
}node, *pNode;

int max1 = 0;
int daan = 0;

//创建二叉搜索树
pNode buildTree(pNode &tree, int num,int tall){

    if(tree == NULL){
        tree = new node;  //开辟空间
        tree->val = num;  //赋值
        tree->left = tree->right = NULL;
        tree->tall = tall;//深度
        if(tall > max1){ //记录最大深度
            max1 = tall;
        }
 //cout << "22" << ' ' << tree->val <<endl;
        return tree;
    }

    //用二层搜索树的性质递归插入结点
    if(num <= tree->val){
        tree->left = buildTree(tree->left, num, tall+1);
    }
    else {
        tree->right = buildTree(tree->right, num, tall+1);
    }

    return tree;
}

//中序遍历
void inOrder(pNode &root){
    if(root == NULL)
        return;

    inOrder(root->left);
    if(root->tall >= max1-1){  //如果是最下两层,答案daan+1
        daan++;
    }
    inOrder(root->right);

}



int main(){
    int n;
    cin >> n;
    int num;
    node *root = NULL;
    for(int i = 0; i < n; i++){
        cin >> num;
        buildTree(root, num, 1);
    }
    //cout << max1 << endl;
    inOrder(root);
    cout << daan;

    return 0;
}


Guess you like

Origin blog.csdn.net/weixin_63484669/article/details/129970725