pat 1115. Counting Nodes in a BST (30)

来源:互联网 发布:java中prototype 编辑:程序博客网 时间:2024/05/21 10:34

https://www.patest.cn/contests/pat-a-practise/1115


#include <cstdio>typedef struct node {int v;struct node * left, * right;node(int x) :left(NULL),right(NULL){v = x;}}Node;int deep,n1,n2;void insertBST(Node *&root, int x,int l) {if (root == NULL) {root = new node(x);if (l > deep) deep = l;return ;}if (x <= root->v) {insertBST(root->left, x, l + 1);}else {insertBST(root->right, x, l + 1);}return ;}void dfs(Node * root,int l) {if (root == NULL) return;if (l == deep) {n1++;}else if (l == deep - 1) {n2++;}dfs(root->left,l+1);dfs(root->right, l + 1);}int main(){int n,x;Node * root = NULL;deep = 0,n1=0,n2=0;scanf("%d",&n);for (int i = 0; i < n; i++){scanf("%d", &x);insertBST(root, x, 0);}dfs(root,0);printf("%d + %d = %d\n", n1, n2, n1 + n2);    return 0;}


0 0
原创粉丝点击