先序顺序输入结点值创建二叉树,并按先序,中序和后序遍历输出

时间:2023-01-09 08:21:14

将如图所示的二叉树通过先序的顺序输入根据其值创建二叉树,如果某个节点其左子树为空,则用 * 代替其左子树节点值,如果某个节点其右子树为空,则用 * 代替其右子树节点值,按照此方式一次性输入节点值用空格隔开就可以得到先序,中序,后序遍历输出

先序顺序输入结点值创建二叉树,并按先序,中序和后序遍历输出
先序顺序输入结点值创建二叉树,并按先序,中序和后序遍历输出

Copyright vivi_and_qiao liwei
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 先序顺序输入结点值创建二叉树_并按先序_中序和后序遍历输出
{
public struct value
{
public static string inputStr;
public static string[] valueStr;
public static int i = 0;
}
public class tree
{
public string data { get; set; }
public tree lchild { get; set; }
public tree rchild { get; set; }
}
public static class Operation
{
public static void Create(tree t)
{
string temp = value.valueStr[value.i++];
//Console.WriteLine("读取了字符" + temp);
if (temp == '*'.ToString())
{
t.lchild = null ;
t.rchild = null;
}
else
{
t.data = temp;
tree lchild=new tree();
tree rchild = new tree();
t.lchild = lchild;
t.rchild = rchild;
Operation.Create(t.lchild);
Operation.Create(t.rchild);
}
}
public static void preorder_traversal(tree t)
{
if (t == null)
return;
else
{
if (t.data != null)
Console.Write(t.data+" ");
preorder_traversal(t.lchild);
preorder_traversal(t.rchild);
}
}
public static void inorder_traversal(tree t)
{
if (t == null)
return;
else
{
inorder_traversal(t.lchild);
if(t.data!=null)
Console.Write(t.data+" ");
inorder_traversal(t.rchild);
}
}
public static void postorder_traversal(tree t)
{
if (t == null)
return;
else
{
postorder_traversal(t.lchild);
postorder_traversal(t.rchild);
if (t.data != null)
Console.Write(t.data+" ");
}
}
}
class Program
{
static void Main(string[] args)
{
value.inputStr = Console.ReadLine();
value.valueStr = value.inputStr.Split(' ');
tree t = new tree();
Operation.Create(t);
Console.WriteLine("先序遍历:");
Operation.preorder_traversal(t);
Console.WriteLine('\n'+"中序遍历:");
Operation.inorder_traversal(t);
Console.WriteLine('\n'+"后序遍历:");
Operation.postorder_traversal(t);
Console.ReadKey();
}
}
}