1115. Counting Nodes in a BST (30)
来源:互联网 发布:金融电子化公司 知乎 编辑:程序博客网 时间:2024/05/16 06:37
题目详情:https://www.patest.cn/contests/pat-a-practise/1115
感觉很简单,但是没有写temp->left=NULL
和 temp->right=NULL
导致程序写错了,想了好长时间!特此纪念!
#include <iostream>#include <malloc.h>#include <vector>using namespace std;typedef struct BSTree{ struct BSTree* left; int data,level;//level存储该节点所在的层次 struct BSTree* right;}BSTree;BSTree* insert(BSTree* root,int value){ if(root==NULL)//找到插入位置 { BSTree* temp=(BSTree*)malloc(sizeof(BSTree)); temp->left=NULL;temp->right=NULL; //没写这两句话居然错了 temp->data=value; return temp; } else if( root->data >= value )//根节点的值较大,则需要到左子树上去找插入位置 { root->left=insert(root->left,value); } else//root->data < value,去右子树上找插入位置 { root->right=insert(root->right,value); } return root;}vector<int> levelOrder(BSTree* root){ vector<int> num_level;//存储每层节点的个数 vector<BSTree*> queue;//存储树节点的队列 BSTree* temp; root->level=1;//根节点的层次设置为1 int front=0;//队列中未访问的第一个节点 queue.push_back(root); while( front!=queue.size() ) { temp=queue[front]; if(temp->left) { temp->left->level=temp->level+1; //层次加1 queue.push_back(temp->left);//把左节点加入到队列中 } if(temp->right) { temp->right->level=temp->level+1;//层次加1 queue.push_back(temp->right);//把右节点加入到队列中 } if(num_level.size()>=temp->level)//temp节点所在的节点层次已经在num_level中 num_level[temp->level -1]++;//那么直接将层次的节点个数加1 else//否则把1添加到最后,代表该层次中只有一个节点 num_level.push_back(1); front++; } return num_level;}int main(){ int n,temp; BSTree* root=NULL; scanf("%d",&n); for( int i=0;i<n;++i ) { scanf("%d",&temp); root=insert(root,temp); } vector<int> num_level=levelOrder(root);//可能只有一层节点,测试用例没有这种可能 int length=num_level.size(); cout<<num_level[length-1]<<" + "<<num_level[length-2]<<" = "<<num_level[length-1]+num_level[length-2]<<endl;}
阅读全文
1 0
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)
- 1115. Counting Nodes in a BST (30)[bst+dfs遍历]
- PAT A 1115. Counting Nodes in a BST (30)
- PAT--1115. Counting Nodes in a BST
- 1115. Counting Nodes in a BST
- 1115. Counting Nodes in a BST
- 【PAT】1115. Counting Nodes in a BST
- 1115. Counting Nodes in a BST 解析
- SPOJTime Limit Exceeded 高维前缀和优化+ dp
- Linux系统之下的基本gdb调试
- 如何安装Lavarel How to install Lavarel?
- C6748定时器64位模式
- ReactJS初学
- 1115. Counting Nodes in a BST (30)
- 0001 Maximum Subsequence Sum
- hdu5115(区间dp)
- Java:多态 之 向下转型+Instanceof关键字
- mysql Innodb和mvcc
- 浮点数误差陷阱
- concurrent-5-AQS-Condition
- Hibernate 入门
- Java Collection