一、LeetCode:105. 从前序与中序遍历序列构造二叉树
(1)题目描述
给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。
示例 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
(2)问题分析
利用前序遍历找出根节点,在利用根节点在中序遍历中找出左子树跟右子树,紧接着进行递归即可。
(3)代码实现
class Solution{
public TreeNode buildTree(int[] preorder,int[] inorder){
if(preorder.length==0||inorder.length==0){
return null;
}
return reBuild(preorder,inorder,0,preorder.length-1,0,preorder.length-1);
}
public TreeNode reBuild(int[] preorder,int[] inorder,int pStart,int pEnd,int iStart,int iEnd){
if(pStart>pEnd) return null;
TreeNode root=new TreeNode(preorder[pStart]);
for(int i=iStart;i<=iEnd;i++){
if(root.val==inorder[i]){
int len=i-iStart;
root.left=reBuild(preorder,inorder,pStart+1,pStart+len,iStart,i-1);
root.right=reBuild(preorder,inorder,pStart+1+len,pEnd,i+1,iEnd);
break;
}
}
return root;
}
}
二、LeetCode:106. 从中序与后序遍历序列构造二叉树
(1)问题描述
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
(2)问题分析
这道题主要是利用中序跟后续重建二叉树,与上一道题是相同的,只不过这里用后续遍历找出根节点,随后利用后序遍历的根节点找出左右子树的根节点,是先遍历即可
(3)代码实现
class Solution{
public TreeNode buildTree(int[] inorder,int[] postorder){
return helper(inorder,postorder,postorder.length-1,0,inorder.length-1);
}
public TreeNode helper(int[] inorder,int[] postorder,int postEnd,int inStart,int inEnd){
if(inStart>inEnd){
return null;
}
int currentVal=postorder[postEnd];
TreeNode current=new TreeNode(currentVal);
int inIndex=0;
for(int i=inStart;i<=inEnd;i++){
if(inorder[i]==currentVal){
inIndex=i;
}
}
TreeNode left = helper(inorder,postorder, postEnd - (inEnd- inIndex) - 1, inStart, inIndex - 1);
TreeNode right = helper(inorder, postorder, postEnd - 1, inIndex + 1, inEnd);
current.left = left;
current.right = right;
return current;
}
}
1260

被折叠的 条评论
为什么被折叠?



