class TreeNode {//二叉树储存结构
char val;
TreeNode left;
TreeNode right;
TreeNode(char x) {
val = x;
}
}
//上述问题的解法都写在TREE类里
class TREE {
public TreeNode buildTree(char[] preorder, char[] inorder) {//由前序遍历与中序遍历创建二叉树
int preLen = preorder.length;
int inLen = inorder.length;
if (preLen != inLen) {
throw new RuntimeException("Incorrect input data.");//前序遍历中序遍历长度不一样要报错
}
return buildTree(preorder, 0, preLen - 1, inorder, 0, inLen - 1);
}
public TreeNode buildTree(char[] preorder,int prel,int prer,
char []inorder,int inl,int inr)
{
if(prel > prer||inl > inr)
return null;//退出条件
char pivot=preorder[prel];//找到根节点
TreeNode root=new TreeNode(pivot);//存入
int pivotindex=inl;
while(inorder[pivotindex]!=pivot)//在中序遍历找到根节点
{
pivotindex++;
}
root.left=buildTree(preorder,prel+1,prel-inl+pivotindex,inorder,inl,pivotindex-1);
root.right=buildTree(preorder,prel-inl+pivotindex+1,prer,inorder,pivotindex+1,inr);
return root;
}
public static void cengci(TreeNode root)//层次遍历二叉树
{
Queue<TreeNode> queue=new LinkedList<TreeNode>();//栈,后进先出
queue.add(root);//存入根节点
while(!queue.isEmpty())
{
TreeNode node =queue.remove();
System.out.print(node.val);//输出根节点
if(node.left!=null)
{
queue.add(node.left);//存入左节点
}
if(node.right!=null)
{
queue.add(node.right);//存入右节点
}
}
return ;
}
public static void mybrackets(TreeNode root,StringBuffer s)//二叉树的括号表示法
{//需要的参数有二叉树的头节点root和StringBuffer类变量对象s
if(root==null)
return ;//退出条件
s.append(root.val);//添加节点
if(root.left!=null||root.right!=null)
{
s.append('(');//添加左括号
mybrackets(root.left,s);//添加左节点
s.append(',');//分隔左右节点
mybrackets(root.right,s);//添加右节点
s.append(')');//添加右括号
}
}
}
以前序遍历和中序遍历构成二叉树各变量的含义如下图所示: