Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int *pre = &preorder[0]; int *in = &inorder[0]; return build(pre, in, inorder.size()); } TreeNode *build(int *pre, int *in, int n) { if(n == 0) return nullptr; TreeNode *root = new TreeNode(pre[0]); int i = 0; for(; i<n; i++) { if(in[i] == pre[0]) break; } root->left = build(pre+1, in, i); root->right = build(pre+i+1, in+i+1, n-i-1); return root; }
相关推荐
105.construct_binary_tree_from_preorder_and_inorder_traversal从前序
Javascript 的解决方案Leetcode Problems and interview problems in Javascript10 Regular Expresion Matching.js100 Same Tree.js101 Symmetric Tree.js102 Binary Tree Level Order Traversal.js103 Binary Tree ...
105.construct-binary-tree-from-preorder-and-inorder-traversal (从前序与中序遍历序列构造二叉树) 106.construct-binary-tree-from-inorder-and-postorder-traversal (从中序与后序遍历序列构造二叉树) 112.path-...
construct-binary-tree-from-preorder-and-inorder-traversal 无官方题解 106 construct-binary-tree-from-inorder-and-postorder-traversal 无官方题解 116 populating-next-right-pointers-in-eac
Inorder Traversal 用两个栈实现队列 232. Implement Queue using Stacks 旋转数组的最小数字 153. Find Minimum in Rotated Sorted Array 斐波那契数列 509. Fibonacci Number 跳台阶 70. Climbing Stairs 变态跳...
[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-...
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/...