Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
原题链接:https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
题目:给定一棵树的前序和中序遍历,构建一颗二叉树。
分析:前序遍历的第一个节点为根节点,以此节点在中序遍历中可作为左右子树的分界,递归的遍历即可找到节点间的依存关系。
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode buildTree(int[] preorder,int startpre,int endpre,int[] inorder,int startin,int endin){
if(startpre>endpre || startin>endin)
return null;
int pivot = preorder[startpre];
int index = 0;
for(index=startin;index<=endin;index++){
if(inorder[index]==pivot)
break;
}
TreeNode root = new TreeNode(pivot);
root.left = buildTree(preorder,startpre+1,startpre+(index-startin),inorder,startin,index-1);
root.right = buildTree(preorder,startpre+(index-startin)+1,endpre,inorder,index+1,endin);
return root;
}
// Definition for binary tree
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
reference : http://zhangzhenyuan163.blog.163.com/blog/static/8581938920129524612517/