根据二叉树的前中序遍历输出二叉树

首先给定两个数组pre[] 和 in[],里面分别存着给定二叉树的前序遍历和中序遍历,下面我们来分析:

  1. 根据前序遍历的特点,前序遍历的第一个节点便是二叉树的头结点head;
  2. 头结点后紧接着的元素便是头结点的左子树,即head.left;
  3. 根据中序遍历的特点,头结点后紧接的元素便是头结点的右子树,即head.right;
  4. 根据这个特点,我们便通过递归来完成这个过程

 

public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;

      TreeNode(int x) {
          val = x;
      }
}
 public static TreeNode buildTree(int[] preorder, int[] inorder) {
        TreeNode head = test(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
        return head;
    }
    public static TreeNode test(int[] pre, int[] in,int pl,int pr,int il,int ir){
        System.out.println(pl+" "+pr+" "+il+" "+ir);
        if(pl > pr){ //递归退出条件
            return null;
        }else if( pl == pr){
            return new TreeNode(pre[pl]);
        }
        int index = pl;
        TreeNode head = new TreeNode(pre[pl]);//头结点后紧接的元素便是head的左?右 子树
        for(int i = index ; i <= ir; i++){
            if(pre[pl] == in[i]){ //寻找头节点
                head.left = test(pre,in,   pl+1    ,pl+i-il   , il ,  i-1);
                head.right = test(pre, in ,pl+i-il+1 ,  pr,     i+1,     ir);
                break;
            }
        }
        return head;
    }

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据二叉树中序遍历和后序遍历输出前序遍历的方法如下: 1. 首先,我们知道前序遍历的顺序是:根节点 -> 左子树 -> 右子树。 2. 后序遍历的顺序是:左子树 -> 右子树 -> 根节点。 3. 中序遍历的顺序是:左子树 -> 根节点 -> 右子树。 根据以上信息,我们可以得出以下步骤来输出前序遍历: 1. 后序遍历的最后一个节点一定是根节点。 2. 在中序遍历中找到根节点的位置,将中序遍历分为左子树和右子树。 3. 根据中序遍历中左子树和右子树的节点数量,将后序遍历分为左子树和右子树。 4. 递归地对左子树和右子树进行相同的操作,直到只剩下一个节点。 5. 输出节点的值,然后递归地输出左子树和右子树的节点值。 下面是一个示例代码来实现这个过程: ```python def build_preorder(inorder, inorder_start, inorder_end, postorder, postorder_start, postorder_end): if inorder_start > inorder_end: return [] root_val = postorder[postorder_end] root_index = inorder.index(root_val) left_size = root_index - inorder_start right_size = inorder_end - root_index left_preorder = build_preorder(inorder, inorder_start, root_index - 1, postorder, postorder_start, postorder_start + left_size - 1) right_preorder = build_preorder(inorder, root_index + 1, inorder_end, postorder, postorder_end - right_size, postorder_end - 1) return [root_val] + left_preorder + right_preorder def get_preorder(inorder, postorder): return build_preorder(inorder, 0, len(inorder) - 1, postorder, 0, len(postorder) - 1) # 示例输入 inorder = [4, 2, 5, 1, 6, 3, 7] postorder = [4, 5, 2, 6, 7, 3, 1] preorder = get_preorder(inorder, postorder) print(preorder) ``` 输出结果为:[1, 2, 4, 5, 3, 6, 7]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值