标签:style blog color strong io for ar div
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 binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *buildTree(vector<int> &preorder,vector<int> &inorder) { int len = inorder.size(); return build(preorder,0,len-1,inorder,0,len-1); } private: TreeNode * build(vector<int> &preorder,int begpreorder,int endpreorder,vector<int> &inorder,int begInorder,int endInorder){ if(begInorder>endInorder || begpreorder>endpreorder) return NULL; int val = preorder[begpreorder]; TreeNode *root = new TreeNode(val); if(endInorder==begInorder) return root; int i,j=0; for(i=begInorder;i<=endInorder;i++,j++){ if(inorder[i]==val) break; } root->left = build(preorder,begpreorder+1,begpreorder+j,inorder,begInorder,i-1); root->right = build(preorder,begpreorder+1+j,endpreorder,inorder,i+1,endInorder); return root; } };
[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal,布布扣,bubuko.com
[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
标签:style blog color strong io for ar div
原文地址:http://www.cnblogs.com/Xylophone/p/3891003.html