新博文地址:
[leetcode]Construct Binary Tree from Preorder and Inorder Traversal
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.
Note:
You may assume that duplicates do not exist in the tree.
根据前序遍历和中序遍历构建二叉树,构建二叉树必须要有中序遍历,前序和后序可选其一。如果对建树过程不太熟悉的朋友,可以看这里。里面很详细的讲解了二叉树的重构过程。算法肯定是一样的,就不多说了,大家可以看这里,代码如下:
public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder.length <= 0){ return null; } if(preorder.length == 1){ return new TreeNode(preorder[0]); } TreeNode root = new TreeNode(preorder[0]); int[] leftInorder = getSubArray(inorder, root.val); int[] rightInorder = Arrays.copyOfRange(inorder, leftInorder.length + 1, inorder.length); int[] leftPreOrder = Arrays.copyOfRange(preorder, 1, leftInorder.length + 1); int[] rightPreOrder = Arrays.copyOfRange(preorder, leftPreOrder.length + 1, preorder.length); root.left = buildTree(leftPreOrder, leftInorder); root.right = buildTree(rightPreOrder, rightInorder); return root; } private int[] getSubArray(int[] inorder,int rootVal){ int length = 0; for(length = 0; length < inorder.length; length++){ if(inorder[length] == rootVal){ break; } } return Arrays.copyOf(inorder, length); }
相关推荐
105.construct_binary_tree_from_preorder_and_inorder_traversal从前序
java java_leetcode题解之Construct Binary Tree from String.java
python python_leetcode题解之094_Binary_Tree_Inorder_Traversal
c语言基础 c语言_leetcode题解之0094_binary_tree_inorder_traversal.zip
javascript js_leetcode题解之94-binary-tree-inorder-traversal.js
python python_leetcode题解之144_Binary_Tree_Preorder_Traversal
javascript js_leetcode题解之144-binary-tree-preorder-traversal.js
python python_leetcode题解之106_Construct_Binary_Tree_from_Inorder
js js_leetcode题解之106-construct-binary-tree-from-inorder
94.Binary_Tree_Inorder_Traversal二叉树的中序遍历【LeetCode单题讲解系列】
java java_leetcode-107-binary-tree-level-order-traversal
java java_leetcode-102-binary-tree-level-order-traversal
java java_leetcode-105-construct-binary-tree-from-preorder-and-inorde
python python_leetcode题解之102_Binary_Tree_Level_Order_Traversal
python python_leetcode题解之107_Binary_Tree_Level_Order_Traversal_II
js js_leetcode题解之102-binary-tree-level-order-traversal.js
144.Binary_Tree_Preorder_Traversal二叉树的前序遍历【LeetCode单题讲解系列】
js js_leetcode题解之107-binary-tree-level-order-traversal-ii.js
java java_leetcode题解之Construct String from Binary Tree.java
python python_leetcode题解之105_Construct_Binary_Tree_from_Preorder