1115. Counting Nodes in a BST (30) Data Structure

 
 

Given a BST tree, find the number of nodes in the last two layers of this number

is given in the form c1+c2 = n

Build tree depth search

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
using namespace std;

struct node{
	int l,r,x;
}n[2010];
int tag,root=1,step,c1,c2;

int insert(int rt,int val,int st){
    step = max(step,st);
	if(rt!=1111){
		if(val<=n[rt].x)n[rt].l = insert(n[rt].l,val,st+1);
		else n[rt].r = insert(n[rt].r,val,st+1);
		return rt;//******if empty here!
	}
	else{
		tag++;
		n[tag].x = val;
		n[day].l = n[day].r = 1111;
		return tag;
	}
}
void dfs(int rt,int st){
    if(rt!=1111){
        if(n[rt].l!=1111)dfs(n[rt].l,st+1);
        if(st==step)c1++;
        else if(st==step-1)c2++;

        if(n[rt].r!=1111)dfs(n[rt].r,st+1);
    }
}
intmain()
{
	int N;
	cin>>N;
	root = 1111;
	for(int i=1;i<=N;i++){
		int val;
		cin>>val;
		root = insert(root,val,1);
	}

	dfs(root,1);
	cout<<c1<<" + "<<c2<<" = "<<c1+c2<<endl;
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325763281&siteId=291194637