AcWing
  • 首页
  • 题库
  • 题解
  • 分享
  • 问答
  • 活动
  • 应用
  • 吐槽
  • 登录/注册

AcWing 1605. 二叉搜索树最后两层结点数量    原题链接    中等

作者: 作者的头像   王小强 ,  2021-02-22 21:35:44 ,  阅读 17


2


二叉树的各种基本功!

#include <iostream>
#include <queue>

using namespace std;
int n, n1, n2;

struct TreeNode {
  int val;
  TreeNode *left, *right;
  TreeNode(int _val) : val(_val), left(nullptr), right(nullptr) {};
  ~TreeNode() {};
};

TreeNode* insertIntoBST(TreeNode* root, int val) {
  // recursion exit condition
  if (!root) return new TreeNode(val);
  if (val <= root->val)
    root->left = insertIntoBST(root->left, val);
  else if (val > root->val)
    root->right = insertIntoBST(root->right, val);
  return root;
}

void inOrder(TreeNode* root) {
  if (!root) return;
  inOrder(root->left);
  printf("%d ", root->val);
  inOrder(root->right);
}

int maxDepth(TreeNode* root) {
  return root ? 1 + max(maxDepth(root->left), maxDepth(root->right)) : 0;
}

int main(void) {
  scanf("%d", &n);

  TreeNode* root = nullptr;
  while (n--) {
    int val;
    scanf("%d", &val);
    root = insertIntoBST(root, val);
  }

  int depth = maxDepth(root);
  // inOrder(root);
  queue<TreeNode*> q{{root}};

  int level = 1;
  while (not q.empty()) {
    int sz = q.size();
    if (level == depth) n1 = sz;
    else if (level == depth - 1) n2 = sz;
    while (sz--) {
      auto cur = q.front(); q.pop();
      if (cur->left)  q.emplace(cur->left);
      if (cur->right) q.emplace(cur->right);
    }
    ++level;
  }

  printf("%d + %d = %d\n", n1, n2, n1 + n2);
}

0 评论

你确定删除吗?

© 2018-2021 AcWing 版权所有  |  京ICP备17053197号-1
联系我们  |  常见问题
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息