105. 从前序与中序遍历序列构造二叉树
Posted 潜行前行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了105. 从前序与中序遍历序列构造二叉树相关的知识,希望对你有一定的参考价值。
- 从前序与中序遍历序列构造二叉树
给定一棵树的前序遍历 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]
/**
* 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[] preorder, int[] inorder) {
if(preorder.length == 0)
return null;
if(preorder[0] == inorder[0]){
TreeNode root = new TreeNode(preorder[0]);
if(preorder.length > 1){
TreeNode right = buildTree(Arrays.copyOfRange(preorder,1,preorder.length),Arrays.copyOfRange(inorder,1,preorder.length));
root.right = right;
return root;
}
}
for( int i=0;i<preorder.length;i++){
if(preorder[0] == inorder[i]){
TreeNode left = buildTree(Arrays.copyOfRange(preorder,1,i+1),Arrays.copyOfRange(inorder,0,i));
TreeNode right = buildTree(Arrays.copyOfRange(preorder,i+1,preorder.length),Arrays.copyOfRange(inorder,i+1,preorder.length));
TreeNode root = new TreeNode(preorder[0]);
root.left = left;
root.right = right;
return root;
}
}
return null;
}
}
以上是关于105. 从前序与中序遍历序列构造二叉树的主要内容,如果未能解决你的问题,请参考以下文章
leetcode-105,106 从前序与中序遍历序列构造二叉树,从中序与后序遍历序列构造二叉树