题解 | #树查找#结点忘记加入队列了,debug了好久
树查找
https://www.nowcoder.com/practice/9a10d5e7d99c45e2a462644d46c428e4
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <stack> #include <map> #include <queue> #include <cmath> using namespace std; struct TreeNode { TreeNode* leftChild; TreeNode* rightChild; int data; }; queue<TreeNode*> que; int main() { int n; while (scanf("%d", &n) != EOF) { TreeNode* root = new TreeNode; //创造一个根结点 root->leftChild = NULL; root->rightChild = NULL; scanf("%d", &root->data); //输入根结点的值 que.push(root); //把根结点放入队列 int curNodeNum = 1; while (curNodeNum < n) { //当前结点数量 < 要求的结点数量 TreeNode* t = new TreeNode; //创建一个新的结点 t->leftChild = NULL; t->rightChild = NULL; scanf("%d", &t->data); //输入该结点的值 TreeNode* cur = que.front(); //当前队头结点 que.pop(); cur->leftChild = t; //把 t 放到 当前队头结点 的 左孩子 que.push(t); //放入队列中 if (++curNodeNum >= n) { //如果加入这个结点以后就没了,就退出循环 break; } TreeNode* t1 = new TreeNode; //再进行一次以上操作 t1->leftChild = NULL; t1->rightChild = NULL; scanf("%d", &t1->data); cur->rightChild = t1; //放在右子树 que.push(t1); if (++curNodeNum >= n) { break; } } int d; scanf("%d", &d); int total = 0; int two = 1; //计算一下在d这个深度有没有结点 for (int j = 1; j < d; j++) { total += two; two *= 2; } if (n <= total) { printf("EMPTY\n"); continue; } int curdeep = 1; while (!que.empty()) { que.pop(); } que.push(root); while (curdeep != d) { int size = que.size(); for (int i = 0; i < size; i++) { TreeNode* curnode = que.front(); que.pop(); if (curnode->leftChild != NULL) { que.push(curnode->leftChild); } if (curnode->rightChild != NULL) { que.push(curnode->rightChild); } } curdeep++; } //curdeep == d int size = que.size(); for (int i = 0; i < size; i++) { TreeNode* curnode = que.front(); que.pop(); printf("%d ", curnode->data); } printf("\n"); } }