LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal
程序员文章站
2022-06-18 18:47:17
...
1.
2
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder==null||preorder.length==0||inorder==null||inorder.length==0||
preorder.length!=inorder.length){
return null;
}
return buildTreeCore(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode buildTreeCore(int[] preorder, int preLeft, int preRight, int[] inorder, int inLeft, int inRight) {
if(preLeft>preRight||inLeft>inRight){
return null;
}
TreeNode root=new TreeNode(preorder[preLeft]);
for(int i=inLeft;i<=inRight;i++){
if(root.val==inorder[i]){
root.left=buildTreeCore(preorder,preLeft+1,preLeft+i-inLeft,inorder,inLeft,i-1);
root.right=buildTreeCore(preorder,preLeft+i-inLeft+1,preRight,inorder,i+1,inRight);
}
}
return root;
}
}
.
推荐阅读
-
LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal
-
LeetCode: 105. Construct Binary Tree from Preorder and Inorder Traversal
-
leetcode 随笔 Construct Binary Tree from Preorder and Inorder Traversal
-
105. Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Preorder and Inorder Traversal
-
LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal
-
LeetCode 94. Binary Tree Inorder Traversal
-
105. Construct Binary Tree from Preorder and Inorder Traversal
-
LeetCode106. Construct Binary Tree from Inorder and Postorder Traversal