给定二叉树的前序和中序遍历,重构这课二叉树.
TreeNode* addNode(vector<int> &preorder, int& start1, vector<int>& inorder, int start2, int end2) { if(start1 >= preorder.size() || end2 < start2) { //doesn't has left branch --start1; return NULL; } //construct the root node TreeNode *root = new TreeNode(preorder[start1]); int i;//the index of current root in inorder for ( i = start2; i <= end2; ++i) { if(inorder[i] == preorder[start1]) break; } //construct left branch root->left = addNode(preorder, ++start1, inorder, start2, i - 1); // construct right branch root->right = addNode(preorder, ++start1, inorder, i + 1, end2); return root; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if(preorder.size() <= 0) return NULL; int start = 0; TreeNode *root = addNode(preorder, start, inorder, 0, inorder.size() - 1); return root; }
TreeNode *createTree(vector<int>& preorder, int left1, int right1, vector<int>&inorder, int left2, int right2) { if(right1 < left1 || right2 < left2 ) return NULL; TreeNode *root = new TreeNode(preorder[left1]); int i = left2; for(; i <= right2; ++i){ if(inorder[i] == preorder[left1]) break; } if(i > right2) return NULL; root->left = createTree(preorder, left1 + 1, left1 + i - left2, inorder, left2, i - 1); root->right = createTree(preorder, left1 + i - left2 + 1, right1, inorder, i + 1, right2); return root; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if(preorder.size() == 0 || inorder.size() == 0 || preorder.size() != inorder.size()) return NULL; TreeNode *root = createTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); return root; }
【leetcode】Construct Binary Tree from Preorder and Inorder Traversal,布布扣,bubuko.com
【leetcode】Construct Binary Tree from Preorder and Inorder Traversal
原文地址:http://blog.csdn.net/shiquxinkong/article/details/28880539