谁能帮我写一个java程序,运行结果如下: 急!!!

2024-11-07 18:18:53
有2个网友回答
网友(1):

System.out.println("急!!!");
不知道你问的是这不0 0~!

网友(2):

终止搞定,inorder和postorder分别是中序和后序
public class Test
{
static String inorder = "287413695";//"BDEFACHG"; //已知中序
static String postorder = "874296531";//"FEDBHGCA"; //已知后序
static Node root;

static class Node
{
public Node(char divideChar)
{
this.data = divideChar;
}

Node left;
Node right;
char data;
}

static Node divide(String in,String post,Node node)
{
if (in == null || in.length() < 1 || post == null || post.length() < 1)
return null;

String left = "";
char divideChar = post.charAt(post.length()-1);

if(in.indexOf(divideChar) != -1)
left = in.substring(0, in.indexOf(divideChar));

String right = in.substring(in.indexOf(divideChar) + 1);

if(node == null)
root = node = new Node(divideChar);
else
node = new Node(divideChar);

if (left != null)
{
if(left.length() > 1)
node.left = divide(left, post.substring(0,left.length()),node);
else if(left.length() == 1)
node.left = new Node(left.charAt(0));
}

if (right != null)
{
if(right.length() > 1)
node.right = divide(right, post.substring(left.length(),post.length()-1),node);
else if(right.length() == 1)
node.right = new Node(right.charAt(0));
}
return node;
}

static void preorder(Node node)
{
if(node == null) return;
System.out.println(node.data);

if(node.left != null) preorder(node.left);
if(node.right != null) preorder(node.right);
}

public static void main(String[] args)
{
root = divide(inorder, postorder,root);
preorder(root); //打印前序
}
}