Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
// construct tree from preorder and inorder class Solution { public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if(preorder.size() == 0) return NULL; return buildTree(preorder, 0, inorder, 0, preorder.size()); } TreeNode *buildTree(vector<int> &pre, int preStart, vector<int> &in, int inStart, int len) { if(preStart < 0 || preStart + len > pre.size() || inStart < 0 || inStart + len > in.size() || len < 1) { return NULL; } int rootVal = pre[preStart]; int i = 0; while(in[i] != rootVal) ++i; TreeNode *root = new TreeNode(rootVal); int leftLen = i - inStart; int rightLen = len - leftLen - 1; root->left = buildTree(pre, preStart+1, in, inStart, leftLen); root->right = buildTree(pre, preStart+leftLen+1, in, i+1, rightLen); return root; } };
欢迎关注微信公众号——计算机视觉:
相关推荐
105.construct_binary_tree_from_preorder_and_inorder_traversal从前序
Inorder Traversal 用两个栈实现队列 232. Implement Queue using Stacks 旋转数组的最小数字 153. Find Minimum in Rotated Sorted Array 斐波那契数列 509. Fibonacci Number 跳台阶 70. Climbing Stairs 变态跳...
421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [C++](./C++/maximum-xor-of-two-numbers-in-an-array.cpp) [Python](./Python/...
105.construct-binary-tree-from-preorder-and-inorder-traversal (从前序与中序遍历序列构造二叉树) 106.construct-binary-tree-from-inorder-and-postorder-traversal (从中序与后序遍历序列构造二叉树) 112.path-...
[105_construct-binary-tree-from-preorder-and-inorder-traversal.cpp] [106_construct-binary-tree-from-inorder-and-postorder-traversal.cpp] [107_binary-tree-level-order-traversal-ii.cpp] [108_convert-...
construct-binary-tree-from-preorder-and-inorder-traversal 无官方题解 106 construct-binary-tree-from-inorder-and-postorder-traversal 无官方题解 116 populating-next-right-pointers-in-eac
14. **重建二叉树**(Construct Binary Tree from Inorder and Postorder Traversal / Preorder Traversal) - 知识点:二叉树,递归,序列化与反序列化 - 解题策略:根据中序和后序/前序遍历序列,通过递归构建...
- **中序遍历(Inorder Traversal)**:先访问左子树,然后访问根节点,最后访问右子树。这种遍历方式对于二叉搜索树特别有用,因为结果是按值排序的。 - **后序遍历(Postorder Traversal)**:先访问左子树,然后访问...
2. 中序遍历(Inorder Traversal):首先递归地进行中序遍历左子树,然后访问根节点,最后递归地进行中序遍历右子树。对于二叉搜索树(BST),中序遍历能以升序访问树中的所有节点。 3. 后序遍历(Postorder ...