1115 Counting Nodes in a BST(30 分)

先建树,之后BFS或者DFS都可以
BFS:

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node {
    int data, layer;
    node *lchild, *rchild;
};
int n1, n2, lowest, above;
node* Newnode(int x)
{
    node* newnode = new node;
    newnode->data = x;
    newnode->lchild = newnode->rchild = NULL;
    return newnode;
}
void insert(node* &root, int x)
{
    if (root == NULL)
    {
        root = Newnode(x);
        return;
    }
    if (x <= root->data)insert(root->lchild, x);
    else if (x > root->data)insert(root->rchild, x);
}
int getheight(node* root)
{
    if (root == NULL)
    {
        return 0;
    }
    return max(getheight(root->lchild), getheight(root->rchild)) + 1;
}
void BFS(node* root)
{
    queue<node*>q;
    root->layer = 1;
    q.push(root);
    while (!q.empty())
    {
        node* front = q.front();
        if (front->layer == lowest)n1++;
        else if (front->layer == above)n2++;
        q.pop();
        if (front->lchild)
        {
            node* child = front->lchild;
            child->layer = front->layer + 1;
            q.push(child);
        }
        if (front->rchild)
        {
            node* child = front->rchild;
            child->layer = front->layer + 1;
            q.push(child);
        }
    }
}
int main()
{
    int n;
    scanf("%d", &n);
    node *root = NULL;
    for (int i = 0; i < n; i++)
    {
        int x;
        scanf("%d", &x);
        insert(root, x);
    }
    int h = getheight(root);
    lowest = h, above = h - 1;
    BFS(root);
    printf("%d + %d = %d", n1, n2, n1 + n2);
    return 0;
}

DFS:

//main里面写
DFS(root,1);
///////
void DFS(node* root, int h)
{
    if (root == NULL)return;
    if (h == lowest)n1++;
    if (h == above)n2++;
    if (root->lchild)DFS(root->lchild, h + 1);
    if (root->rchild)DFS(root->rchild, h + 1);
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 一、动态规划 找到两点间的最短路径,找最匹配一组点的线,等等,都可能会用动态规划来解决。 参考如何理解动态规划中,...
    小碧小琳阅读 25,370评论 2 20
  • 此时此刻,周围仿佛都是安静的了,我听不到没有一丁点儿的声音。这个世界又似乎是白色的,只有我一个人,呆呆地跪在地上,...
    向浚恺阅读 3,468评论 5 4
  • 远远地在村口,她看见一个男人正在和莹婆婆说话。 要不是他骑着单车停在那家门口,她也认不出那是他了。她差点以为那是他...
    三小姐的试衣间阅读 1,761评论 0 1
  • 文、摄影/许永杰 2017年8月19日适逢周末,与家人一同前往三原,慕名瞻仰了于右任纪念馆。...
    许永杰阅读 4,101评论 0 0