博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1099. Build A Binary Search Tree (30)
阅读量:4927 次
发布时间:2019-06-11

本文共 2571 字,大约阅读时间需要 8 分钟。

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.

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:

91 62 3-1 -1-1 45 -1-1 -17 -1-1 8-1 -173 45 11 58 82 25 67 38 42

Sample Output:

58 25 82 11 38 67 45 73 42
1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
7 using namespace std; 8 9 struct node10 {11 int l,r,v;12 };13 14 node Tree[110];15 vector
vv;16 int cnt = 0;17 void inOder(int root)18 {19 if(Tree[root].l != -1)20 inOder(Tree[root].l);21 Tree[root].v = vv[cnt++];22 if(Tree[root].r != -1)23 inOder(Tree[root].r);24 }25 26 int main()27 {28 int n,tem;29 scanf("%d",&n);30 for(int i = 0 ;i < n;++i)31 {32 scanf("%d%d",&Tree[i].l,&Tree[i].r);33 }34 35 for(int i = 0 ;i < n;++i)36 {37 scanf("%d",&tem);38 vv.push_back(tem);39 }40 sort(vv.begin(),vv.end());41 inOder(0);42 queue
qq;43 qq.push(Tree[0]);44 bool fir = 1;45 while(!qq.empty())46 {47 node ntem = qq.front();48 qq.pop();49 if(fir)50 {51 fir = 0;52 printf("%d",ntem.v);53 }54 else55 {56 printf(" %d",ntem.v);57 }58 if(ntem.l != -1)59 qq.push(Tree[ntem.l]);60 if(ntem.r != -1)61 qq.push(Tree[ntem.r]);62 }63 printf("\n");64 return 0;65 }

 

转载于:https://www.cnblogs.com/xiaoyesoso/p/5213971.html

你可能感兴趣的文章
实验一质量属性报告
查看>>
PyCharm下的pywin32安装及使用
查看>>
各类有用的神奇网站
查看>>
java配置opencv-在eclipse中
查看>>
nginx 启动脚本
查看>>
地图几何计算
查看>>
共享程序集
查看>>
大数字运算——1、BigInteger
查看>>
实验十 指针2
查看>>
django之Form组件
查看>>
软件工程练习——找水王2
查看>>
php单一入口和多入口模式详细讲解
查看>>
Java 启动线程的方式
查看>>
C语言的多行宏定义
查看>>
windows下安装JDK和Tomcat
查看>>
使用html5兼容低版本浏览器
查看>>
sea.js 学习
查看>>
【软工7】软件工程中的文档
查看>>
C#垃圾回收机制
查看>>
sublime text2 安装less2css插件
查看>>