[LC] 105. Construct Binary Tree from Preorder and Inorder Traversal
Posted xuanlu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 105. Construct Binary Tree from Preorder and Inorder Traversal相关的知识,希望对你有一定的参考价值。
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7] inorder = [9,3,15,20,7]
Return the following binary tree:
3 / 9 20 / 15 7
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { Map<Integer, Integer> mymap = new HashMap<>(); for (int i = 0; i < inorder.length; i++) { mymap.put(inorder[i], i); } return helper(0, inorder.length - 1, 0, preorder.length - 1, preorder, mymap); } private TreeNode helper(int inLeft, int inRight, int preLeft, int preRight, int[] preorder, Map<Integer, Integer> mymap) { if (inLeft > inRight) { return null; } TreeNode cur = new TreeNode(preorder[preLeft]); int leftSize = mymap.get(preorder[preLeft]) - inLeft; // preRight for left just add up leftSize cur.left = helper(inLeft, inLeft + leftSize - 1, preLeft + 1, preLeft + leftSize, preorder, mymap); cur.right = helper(inLeft + leftSize + 1, inRight, preLeft + leftSize + 1, preRight, preorder, mymap); return cur; } }
以上是关于[LC] 105. Construct Binary Tree from Preorder and Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
105. Construct Binary Tree from Inorder and preorder Traversal
105. Construct Binary Tree from Preorder and Inorder Traversal
105. Construct Binary Tree from Preorder and Inorder Traversal
105. Construct Binary Tree from Preorder and Inorder Traversal
105.Construct Binary Tree from Preorder and Inorder Traversal
105. Construct Binary Tree from Preorder and Inorder Traversal