从中序与后序遍历序列构造二叉树
leetcode 106 题 从中序与后序遍历序列构造二叉树
leetcode 106:从中序与后序遍历序列构造二叉树 原题链接
题目描述:
解题思路
解题代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return process(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
}
/**
* 递归去组建树
* is 是左子树起始位置,
* ie 是左子树结束位置
* ps 右子树起始位置
* pe 右子树结束位置
*/
public TreeNode process(int[]inorder,int is,int ie,int[]postorder,int ps,int pe){
//base case
if(is > ie || ps > pe){
return null;
}
//根据后序遍历的头节点来去找中序遍历头节点位置,把数组分成左树和右树。
int headVal = postorder[pe];
int index = 0;
for(int i = is; i <= ie;i++){
if(inorder[i] == headVal){
index = i;
break;
}
}
//左子树的长度
int leftSize = index - is;
TreeNode head = new TreeNode(headVal);
head.left = process(inorder,is,index-1,postorder,ps,ps+leftSize-1);
head.right = process(inorder,index+1,ie,postorder,ps+leftSize,pe-1);
return head;
}
}
二叉树专题
从前序与中序遍历序列构造二叉树
leetcode二叉树中的最大路径和
二叉树的序列化和反序列化
求两个节点的最低公共祖先
给定一棵二叉树的头节点,返回这颗二叉树中最大的二叉搜索子树的头节点
计算二叉树中最大的二叉搜索子树的大小(节点数量)