.建立并中序遍历一个排序二叉树
排序二叉树是指左子树的所有节点的值均小于它根节点的值,右子树的所有节点的值均大于它根节点的值,如下图是一棵排序二叉树
输入:
输入有一行,表示若干个要排序的数,输入0时停止
输出
二叉树的凹入表示
和二叉树的中序遍历序列
sample:
input:
56 78 34 89 12 35 67 77 22 57 0
output:
12
22
34
35
56
57
67
77
78
89
12 22 34 35 56 57 67 77 78 89
测试输入 | 期待的输出 | 时间限制 | 内存限制 | 额外进程 | |
---|---|---|---|---|---|
测试用例 1 | 以文本方式显示
| 以文本方式显示
| 无限制 | 64M | 0 |
测试用例 2 | 以文本方式显示
| 以文本方式显示
| 无限制 | 64M | 0 |
代码如下:
由于那个什么“连山杯”嘛什么的东西,现在不得不学C++了(要是20号8:00前学完就报一下那个,不过到时候估计没有队友了,为什么今年没有单人队啊呜呜,估计今年是参加不了了),C语言单推人的失败!!!(主要用C写真的好慢啊,估计不是很方便,java又没向数据结构深挖,虽然可能数据结构都差不多,但是我java属实是需要一边搜一遍敲的那种,完全记不到库啊之类的,主要写的少了)
好了,把这次的代码写了,才发现现在可以交其他语言,比如python和java还有C#了,正好练了一下:
C++代码
#include <iostream>
using namespace std;
struct node
{
int data;
node *left;
node *right;
};
node *Initialize(int Data)
{
node *Node=(node*)malloc(sizeof(node));
Node->data = Data;
Node->left = NULL;
Node->right = NULL;
return Node;
}
node *insertNode(node *&root, int data)
{
if (root == NULL)
{
root = Initialize(data);
return root;
}
if (data < root->data)
insertNode(root->left, data);
else if (data > root->data)
insertNode(root->right, data);
return root;
}
void printTree(node *&root, int space)
{
if (root != NULL)
{
printTree(root->left, space + 4);
for (int i = 0; i < space; i++)
cout << " ";
cout << root->data << endl;
printTree(root->right, space + 4);
}
}
void printInorder(node *root)
{
if (root != NULL)
{
printInorder(root->left);
cout << ' ';
cout << root->data;
printInorder(root->right);
}
}
int main()
{
int num;
node *root = NULL;
cin >> num;
while (num != 0)
{
root = insertNode(root, num);
cin >> num;
}
printTree(root, 0);
cout << endl;
printInorder(root);
cout << endl;
return 0;
}
Java代码
import java.util.Scanner;
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
public class Main {
public static Node newNode(int data) {
Node node = new Node(data);
return node;
}
public static Node insertNode(Node root, int data) {
if (root == null) {
root = newNode(data);
return root;
}
if (data < root.data)
root.left = insertNode(root.left, data);
else if (data > root.data)
root.right = insertNode(root.right, data);
return root;
}
public static void printTree(Node root, int space) {
if (root != null) {
printTree(root.left, space + 4);
for (int i = 0; i < space; i++)
System.out.print(" ");
System.out.println(root.data);
printTree(root.right, space + 4);
}
}
public static void printInorder(Node root) {
if (root != null) {
printInorder(root.left);
System.out.print(" " + root.data);
printInorder(root.right);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
Node root = null;
while (num != 0) {
root = insertNode(root, num);
num = scanner.nextInt();
}
printTree(root, 0);
System.out.println();
printInorder(root);
System.out.println();
scanner.close();
}
}
C++真的和Java好像,顺序应该说反了,不过很像就对了。
很套路的一道题,直接把代码塞到我的记忆md中,下次写类似的直接套上去改代码嘿嘿。