中序和后序生成二叉树

package tree.test;

import java.util.LinkedList;

import tree.domian.TreeNode;

public class Test {
    public static void main(String[] args) {
        String hx = "KBFDCAE";

        String zx = "BKFEACD";

       方法一

//        TreeNode tree = new TreeNode();

//        toTree(tree,hx,zx);

      方法二

        TreeNode tree = createTreeNode(hx,zx);
        print(tree);
    }

    private static TreeNode createTreeNode(String hx, String zx) {
        TreeNode node = new TreeNode();
        int size = hx.length();
        String c = hx.charAt(size-1)+"";

        node.setData(c);

//如果size为1说明它已经到最后一个没有左右孩子直接返回

        if(size==1)

            return node;

//获取后序最后的数即根节点查找在中序中出现的索引的位置

        int index = zx.indexOf(c);

//如果index>0说明它有左孩子

        if(index>0){
              node.setLeftChild(createTreeNode(hx.substring(0, index),zx.substring(0, index)));

            }

//如果index<size-1说明它有右孩子

            if(index<size-1){
              node.setRightChild(createTreeNode(hx.substring(index,size-1),zx.substring(index+1)));

            }

//返回添加孩子后的节点

            return node;
    }

    private static void print(TreeNode tree) {
         if(tree==null){
             System.out.println("null");
             return;
         }
         LinkedList<TreeNode> list = new LinkedList<TreeNode>();
         list.add(tree);
         while(list.size()>0){
             TreeNode temp = list.removeLast();
             String data = temp.getData();
             System.out.println(data+" ");
             TreeNode left = temp.getLeftChild();
             TreeNode right = temp.getRightChild();
             if(left!=null)
             list.addFirst(left);
             if(right!=null)
             list.addFirst(right);
         }
    }

    private static void toTree(TreeNode tree, String hx, String zx) {
        int size = hx.length();
        String c = hx.charAt(size-1)+"";
        
        tree.setData(c);
        if(size==1)
            return;
        int index = zx.indexOf(c);
        if(index>0){
          tree.setLeftChild(new TreeNode());
          toTree(tree.getLeftChild(),hx.substring(0, index),zx.substring(0, index));
        }
        if(index<size-1){
          tree.setRightChild(new TreeNode());
          toTree(tree.getRightChild(),hx.substring(index,size-1),zx.substring(index+1));
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值