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; }
相关推荐
java java_leetcode-105-construct-binary-tree-from-preorder-and-inorde
105.construct_binary_tree_from_preorder_and_inorder_traversal从前序
js js_leetcode题解之105-construct-binary-tree-from-preorder
java java_leetcode-107-binary-tree-level-order-traversal
java java_leetcode-102-binary-tree-level-order-traversal
python python_leetcode题解之105_Construct_Binary_Tree_from_Preorder
javascript js_leetcode题解之144-binary-tree-preorder-traversal.js
js js_leetcode题解之106-construct-binary-tree-from-inorder
java java_leetcode题解之Construct Binary Tree from String.java
python python_leetcode题解之144_Binary_Tree_Preorder_Traversal
javascript js_leetcode题解之94-binary-tree-inorder-traversal.js
python python_leetcode题解之106_Construct_Binary_Tree_from_Inorder
js js_leetcode题解之102-binary-tree-level-order-traversal.js
js js_leetcode题解之107-binary-tree-level-order-traversal-ii.js
python python_leetcode题解之094_Binary_Tree_Inorder_Traversal
c语言基础 c语言_leetcode题解之0094_binary_tree_inorder_traversal.zip
python python_leetcode题解之102_Binary_Tree_Level_Order_Traversal
python python_leetcode题解之107_Binary_Tree_Level_Order_Traversal_II
js js_leetcode题解之103-binary-tree-zigzag-level-order-traversal.js
java java_leetcode-110-balanced-binary-tree