1099 Build A Binary Search Tree (30 point(s))

1099 Build A Binary Search Tree (30 point(s))

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.

figBST.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:

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

Sample Output:

58 25 82 11 38 67 45 73 42

考察点:

1. 知识点:BST的中序遍历是非递减序列;

2. 静态数组建立二叉树;

3. 利用递归完成树的中序遍历;

4. 利用队列完成树的层次遍历。

思路:

根据题目的图片实例和输入方式,此题适当使用结点静态数组保存二叉树。由于这是一棵二叉搜索树,因此只需要将给出的序列排序后,就可以得到它的中序遍历。因此将树的结构建立起来以后,对整棵树中序遍历(左子树--根--右子树),将按照元素大小排序后的序列依次插入二叉搜索树中。

最后借助队列,输出这棵二叉搜索树的层次遍历。

我的代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
struct Node{
	int data;int left,right;
	Node(){	data = 0;left=right=-1;	}
};
Node node[107];
int a[107];
int idx = 0;
void insert(int root){//中序遍历,同时完成赋值 
	if(node[root].left!=-1){
		insert(node[root].left);
	}
	node[root].data = a[idx];idx++;
	if(node[root].right!=-1){
		insert(node[root].right);
	} 
}
vector<Node> levelOrder(){//利用队列完成层次遍历 
	queue<Node> q;
	vector<Node> ans;
	q.push(node[0]);
	while(!q.empty()){
		Node cur = q.front();
		ans.push_back(cur);
		q.pop();
		if(cur.left!=-1) q.push(node[cur.left]);
		if(cur.right!=-1) q.push(node[cur.right]);
	}
	return ans;
}
int main(void){
	int N;cin>>N;
	for(int i=0;i<N;i++){
		cin>>node[i].left>>node[i].right;
	}
	for(int i=0;i<N;i++) cin>>a[i];
	sort(a,a+N); 
	insert(0);
	vector<Node> order = levelOrder();
	for(int i=0;i<order.size();i++){
		if(i==0) cout<<order[i].data;
		else cout<<" "<<order[i].data;
	}
	return 0;
}

 大神更简洁的代码(思路一致):

参考链接:https://blog.youkuaiyun.com/richenyunqi/article/details/80150933

#include<bits/stdc++.h>
using namespace std;
struct Node{
    int data,left=-1,right=-1;
};
Node tree[105];
int data[105],N;
void inOrder(int root,int&index){//中根遍历
    if(root==-1)//root==-1,直接返回
        return;
    inOrder(tree[root].left,index);//递归遍历左子树
    tree[root].data=data[index++];//将数据填入根部结点
    inOrder(tree[root].right,index);//递归遍历右子树
}
void levelOrder(){//层次遍历
    queue<int>q;
    q.push(0);
    while(!q.empty()){
        int t=q.front();
        q.pop();
        printf("%s%d",t==0?"":" ",tree[t].data);
        if(tree[t].left!=-1)
            q.push(tree[t].left);
        if(tree[t].right!=-1)
            q.push(tree[t].right);
    }
}
int main(){
    scanf("%d",&N);
    for(int i=0;i<N;++i)
        scanf("%d%d",&tree[i].left,&tree[i].right);
    for(int i=0;i<N;++i)
        scanf("%d",&data[i]);
    sort(data,data+N);//排序
    int index=0;
    inOrder(0,index);
    levelOrder();
    return 0;
}
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
struct Node{
	int data = INF;int left,right;
	Node(){	data = INF;left=right=-1;	}
};
Node node[107];
int a[107];
int idx = 0;
void insert(int root){//中序遍历,同时完成赋值 
	if(node[root].left!=-1){
		insert(node[root].left);
	}
	node[root].data = a[idx];idx++;
	if(node[root].right!=-1){
		insert(node[root].right);
	} 
}
vector<Node> levelOrder(){//利用队列完成层次遍历 
	queue<Node> q;
	vector<Node> ans;
	q.push(node[0]);
	while(!q.empty()){
		Node cur = q.front();
		ans.push_back(cur);
		q.pop();
		if(cur.left!=-1) q.push(node[cur.left]);
		if(cur.right!=-1) q.push(node[cur.right]);
	}
	return ans;
}
int main(void){
	int N;cin>>N;
	for(int i=0;i<N;i++){
		cin>>node[i].left>>node[i].right;
	}
	for(int i=0;i<N;i++) cin>>a[i];
	sort(a,a+N); 
	insert(0);
	vector<Node> order = levelOrder();
	for(int i=0;i<order.size();i++){
		if(i==0) cout<<order[i].data;
		else cout<<" "<<order[i].data;
	}
	return 0;
}

 

To accomplish this task in English, you would first need to write a short paragraph and then perform the following steps: 1. **Counting letters and their frequencies:** Read through the input text, counting each unique letter along with its occurrences. You can use a dictionary (hash map) to store these counts. 2. **Building a Huffman Tree:** Organize the letter-frequency pairs into a priority queue or a heap data structure. Perform a series of merge operations until there's only one node left, which forms the root of the Huffman tree. Each internal node represents a pair of letters, while leaves represent the individual letters with their frequencies as weights. 3. **Assigning Huffman Codes:** Traverse the tree bottom-up, assigning a '0' for moving left and '1' for right at each decision point. This will give you a unique binary code for each letter. 4. **Encoding the original text:** Replace each letter with its corresponding Huffman code, generating a new encoded string. 5. **Decoding using the Huffman Tree:** Starting from the root, read the bits from the encoded string in sequence, making decisions based on the '0's and '1's until a leaf is reached, which gives you the decoded letter. 6. **Comparing the original and decoded texts:** Finally, compare the original and decoded strings to confirm that the encoding and decoding process was accurate. Here's an example code snippet in Python to demonstrate how you might implement these steps: ```python from collections import Counter import heapq # Step 1: Count characters text = "Your sample text goes here..." char_freq = Counter(text) # Step 2 & 3: Build Huffman Tree heap = [[freq, char] for char, freq in char_freq.items()] heapq.heapify(heap) while len(heap) > 1: lo = heapq.heappop(heap) hi = heapq.heappop(heap) merged_freq = lo[0] + hi[0] heapq.heappush(heap, [merged_freq, [lo[1], hi[1]]]) root, _ = heapq.heappop(heap) # Assign Huffman codes huffman_codes = {char: build_code(root, "") for char, _ in char_freq.items()} # Steps 4 & 5: Encode and decode encoded_text = "".join(huffman_codes[char] for char in text) decoded_text = decode(encoded_text, root) def build_code(node, code): if isinstance(node, list): return build_code(node[0], code + "0") + build_code(node[1], code + "1") else: return code def decode(code, root): if not code: return root bit = code[0] code = code[1:] if isinstance(root, list): return decode(code, root[bit == "0"]) else: return root # Step 6: Compare original and decoded texts if text == decoded_text: print("Encoding and decoding successful!") else: print("Error: Decoded text does not match the original.") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值