用先序序列与中序序列的字符串创建二叉树,并返回二叉树的层次遍历序列以及用括号表示法输出该二叉树 JAVA

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(')');//添加右括号
	   }
   }
}

以前序遍历和中序遍历构成二叉树各变量的含义如下图所示:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值