Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树
通过preorder 和inorder,构造一棵二叉树
思路
问题不复杂,有了前序和中序,可以恢复一棵二叉树。
前序里面打头的肯定是root
中序里面的root,将inorder 分成2份,左侧为左树,右侧为右树。
需要pos 定位root,然后递归buildtree
/**
* 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) {
List<Integer> pre= new ArrayList<>();
List<Integer> in= new ArrayList<>();
int i =0;
while(i<preorder.length){
pre.add(preorder[i]);
i++;
}
i=0;
while(i<inorder.length){
in.add(inorder[i]);
i++;
}
return _buildTree(pre,in);
}
public TreeNode _buildTree(List<Integer> preorder, List<Integer> inorder){
if(preorder.size()==0){return null;}
int pos =0 ;
while(!inorder.get(pos).equals(preorder.get(0))){
pos++;
}
List<Integer> lpre = new ArrayList<>();
List<Integer> lin = new ArrayList<>();
List<Integer> rpre = new ArrayList<>();
List<Integer> rin = new ArrayList<>();
for(int i = 0;i<pos ;i++){
lpre.add(preorder.get(i+1));
lin.add(inorder.get(i));
}
for(int i = pos+1;i<inorder.size();i++){
rpre.add(preorder.get(i));
rin.add(inorder.get(i));
}
TreeNode root = new TreeNode(preorder.get(0)) ;
root.left = _buildTree(lpre,lin);
root.right = _buildTree(rpre,rin);
return root;
}
}
Tag
tree
DFS
Array