/**
* 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;
}
}
LeetCode106:Construct Binary Tree from Inorder and Postorder Traversal
最新推荐文章于 2022-05-29 13:27:49 发布
该博客主要讲解如何根据二叉树的中序和后序遍历来重建原始二叉树。通过深度优先搜索(DFS)的递归策略,解析遍历序列并构建树节点。内容涵盖LeetCode第106题的解题思路与实现方法。
摘要由CSDN通过智能技术生成