【PAT甲级】1115 Counting Nodes in a BST(30 分)(BST,dfs)

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/feng_zhiyu/article/details/82499828

题目链接

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Insert a sequence of numbers into an initially empty binary search tree. Then you are supposed to count the total number of nodes in the lowest 2 levels of the resulting tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤1000) which is the size of the input sequence. Then given in the next line are the N integers in [−10001000] which are supposed to be inserted into an initially empty binary search tree.

Output Specification:

For each case, print in one line the numbers of nodes in the lowest 2 levels of the resulting tree in the format:

n1 + n2 = n

where n1 is the number of nodes in the lowest level, n2 is that of the level above, and n is the sum.

Sample Input:

9
25 30 42 16 20 20 35 -5 28

Sample Output:

2 + 4 = 6

题意:输出一个二叉搜索树的最后两层结点个数a和b,以及他们的和c:“a + b = c”

思路:建立二叉搜索树,dfs

代码:

#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;i++)
#define drep(i,n,a) for(int i=n;i>=a;i--)
#define mem(a,n) memset(a,n,sizeof(a))
#define lowbit(i) ((i)&(-i))
typedef long long ll;
typedef unsigned long long ull;
const ll INF=0x3f3f3f3f;
const double eps = 1e-6;
const int N = 1e5+5;

struct Node{
    int data;
    Node *left, *right;
};
Node* build(Node* root,int x){
    if(root==NULL){
        root=new Node();
        root->data=x;
        root->left=root->right=NULL;
    }else if(root->data>=x){
        root->left=build(root->left,x);
    }else if(root->data<x){
        root->right=build(root->right,x);
    }
    return root;
}
int cnt[N],maxDepth=1;
void dfs(Node* root,int depth){
    if(root==NULL){
        maxDepth=max(maxDepth,depth);
        return ;
    }
    cnt[depth]++;
    dfs(root->left,depth+1);
    dfs(root->right,depth+1);
}
int main(){
    int n,x;
    scanf("%d",&n);
    Node *root=NULL;
    for(int i=0;i<n;i++){
        scanf("%d",&x);
        root=build(root,x);
    }
    dfs(root,1);
    printf("%d + %d = %d",cnt[maxDepth-1],cnt[maxDepth-2],cnt[maxDepth-1]+cnt[maxDepth-2]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/feng_zhiyu/article/details/82499828
今日推荐