Home PAT 1115 Counting Nodes in a Binary Search Tree
Post
Cancel

PAT 1115 Counting Nodes in a Binary Search Tree

Link

练习一下链表建树 2333

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
using namespace std;
#define INF 1010
int n,a,maxv,n1,n2;
struct node{
    int val;
    struct node *left,*right;
}tree[1010];
int num[1010];
node* Insert(node *root,int i){
    if(root==NULL){
        root=new node();
        root->val=i;
        root->left=root->right=NULL;
    }else if(i<=root->val) root->left=Insert(root->left,i); //是root->left=Insert(...)不是root
    else root->right=Insert(root->right,i);
    return root;
}
void DFS(node *root,int depth){
    if(root==NULL){
        maxv=max(maxv,depth-1);
        return;
    }
    num[depth]++;
    DFS(root->left,depth+1);
    // cout<<root->val<<endl;
    DFS(root->right,depth+1);
}
int main() {
    scanf("%d",&n);
    node *root=NULL;
    for(int i=1;i<=n;++i){
        scanf("%d",&a);
        root=Insert(root,a);
    }
    DFS(root,0);
    printf("%d + %d = %d\n",num[maxv],num[maxv-1],num[maxv]+num[maxv-1]);
    return 0;
}
This post is licensed under CC BY 4.0 by the author.