Given inorder and postorder 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>& inorder, vector<int>& postorder) { int *po = &postorder[0]; int *in = &inorder[0]; return build(po, in, inorder.size()); } TreeNode *build(int *po, int *in, int n) { if(n == 0) return nullptr; TreeNode *root = new TreeNode(po[n-1]); int i = 0; for(; i<n; i++) { if(in[i] == po[n-1]) break; } root->left = build(po, in, i); root->right = build(po+i, 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题解之106-construct-binary-tree-from-inorder
java java_leetcode-107-binary-tree-level-order-traversal
java java_leetcode-102-binary-tree-level-order-traversal
js js_leetcode题解之105-construct-binary-tree-from-preorder
javascript js_leetcode题解之144-binary-tree-preorder-traversal.js
python python_leetcode题解之106_Construct_Binary_Tree_from_Inorder
java java_leetcode题解之Construct Binary Tree from String.java
python python_leetcode题解之144_Binary_Tree_Preorder_Traversal
python python_leetcode题解之105_Construct_Binary_Tree_from_Preorder
javascript js_leetcode题解之94-binary-tree-inorder-traversal.js
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