LeetCode106:Construct Binary Tree from Inorder and Postorder Traversal

37 篇文章 0 订阅
26 篇文章 0 订阅
该博客主要讲解如何根据二叉树的中序和后序遍历来重建原始二叉树。通过深度优先搜索(DFS)的递归策略,解析遍历序列并构建树节点。内容涵盖LeetCode第106题的解题思路与实现方法。
摘要由CSDN通过智能技术生成

这里写图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstruct(int[] inorder, int[] postorder,int in_left,int in_right,int po_left,int po_right){
           //边界条件
           if(inorder==null || postorder==null || in_left>in_right || po_left>po_right )  return null;
           if(postorder.length==1 ) {
               TreeNode root = new TreeNode(postorder[0]);
               return root;
            }
               int len=0;   
               //从前序遍历中查找到根节点的下标    
              int index = findIndex(inorder,postorder[po_right],in_left,in_right);
               //后序遍历中 当前子序列中最后一个节点 为根节点
               TreeNode root = new TreeNode(postorder[po_right]);
               len = index-in_left;
               root.left = reConstruct(inorder,postorder,in_left,index-1,po_left,po_left+len-1);
               root.right = reConstruct(inorder,postorder,index+1,in_right,po_left+len,po_right-1);
               return root;
        }
        //查找下标
       public int findIndex(int[] orders,int num,int begin,int end){
           int index=0;
           for(int i=begin;i<=end;i++){
               if(orders[i]==num){
                   index=i;
                   break;
               }
           }
           return index;
       }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder==null || postorder==null) return null;
         TreeNode root = reConstruct(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
         return  root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值