1099. Build A Binary Search Tree (30)

向右看齐 2022-05-30 03:42 262阅读 0赞

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

The left subtree of a node contains only nodes with keys less than the node’s key.The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.Both the left and right subtrees must also be binary search trees.

Given the structure of a binary tree and a sequence of distinct integer keys, there is only one way to fill these keys into the tree so that the resulting tree satisfies the definition of a BST. You are supposed to output the level order traversal sequence of that tree. The sample is illustrated by Figure 1 and 2.

h8_nkqjeu5lglo.jpg

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=100) which is the total number of nodes in the tree. The next N lines each contains the left and the right children of a node in the format “left_index right_index”, provided that the nodes are numbered from 0 to N-1, and 0 is always the root. If one child is missing, then -1 will represent the NULL child pointer. Finally N distinct integer keys are given in the last line.

Output Specification:

For each test case, print in one line the level order traversal sequence of that tree. All the numbers must be separated by a space, with no extra space at the end of the line.

Sample Input:

  1. 9
  2. 1 6
  3. 2 3
  4. -1 -1
  5. -1 4
  6. 5 -1
  7. -1 -1
  8. 7 -1
  9. -1 8
  10. -1 -1
  11. 73 45 11 58 82 25 67 38 42

Sample Output:

  1. 58 25 82 11 38 67 45 73 42

题目大意:

代码:

  1. #include<stdio.h>
  2. #include<algorithm>
  3. #include<queue>
  4. using namespace std;
  5. struct node
  6. {
  7. int data;
  8. int lchild,rchild;
  9. }tree[110];
  10. int arr[110];
  11. int num=0;
  12. void midtraverl(int index)
  13. {
  14. if(index!=-1)
  15. {
  16. midtraverl(tree[index].lchild);
  17. tree[index].data=arr[num++];
  18. midtraverl(tree[index].rchild);
  19. }
  20. }
  21. void leveltraverl(int index)
  22. {
  23. queue<struct node> q;
  24. q.push(tree[index]);
  25. int flag=0;
  26. while(!q.empty())
  27. {
  28. struct node tmp=q.front();
  29. q.pop();
  30. if(tmp.lchild!=-1)
  31. q.push(tree[tmp.lchild]);
  32. if(tmp.rchild!=-1)
  33. q.push(tree[tmp.rchild]);
  34. if(flag==0)
  35. {
  36. printf("%d",tmp.data);
  37. flag=1;
  38. }
  39. else
  40. {
  41. printf(" %d",tmp.data);
  42. }
  43. }
  44. }
  45. int main()
  46. {
  47. int i,j,n,m,k,t;
  48. scanf("%d",&n);
  49. for(i=0;i<n;i++)
  50. {
  51. scanf("%d %d",&tree[i].lchild,&tree[i].rchild);
  52. }
  53. for(i=0;i<n;i++)
  54. {
  55. scanf("%d",&arr[i]);
  56. }
  57. sort(arr,arr+n);
  58. midtraverl(0);
  59. leveltraverl(0);
  60. return 0;
  61. }

发表评论

表情:
评论列表 (有 0 条评论,262人围观)

还没有评论,来说两句吧...

相关阅读