LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
程序员文章站
2022-04-27 11:35:32
...
1.
2.
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(postorder==null||postorder.length==0||inorder==null||inorder.length==0||
postorder.length!=inorder.length){
return null;
}
return buildTreeCore(postorder,0,postorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode buildTreeCore(int[] postorder, int postLeft, int postRight, int[] inorder, int inLeft, int inRight) {
if(postLeft>postRight||inLeft>inRight){
return null;
}
TreeNode root=new TreeNode(postorder[postRight]);
for(int i=inLeft;i<=inRight;i++){
if(root.val==inorder[i]){
root.left=buildTreeCore(postorder,postLeft,postLeft+i-inLeft-1,inorder,inLeft,i-1);
root.right=buildTreeCore(postorder,postLeft+i-inLeft,postRight-1,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: binary-tree-postorder-traversal:后序遍历二叉树
-
LeetCode 94. Binary Tree Inorder Traversal
-
LeetCode145. Binary Tree Postorder Traversal(后序遍历)