Description:
Given arrays recording 'Preorder and Inorder' Traversal (Problem 105) or 'Inorder and Postorder' (Problem 106), u need build the binary tree.
Input:
105. Preorder & Inorder traversal
106. Inorder & Postorder traversal
output:
A binary tree.
Solution:
This solution uses the algorithm "divide and conquer". Taking an example of 105, we can get the root node from preorder travelsal then use inorder traversal to divide the range of left tree nodes and the right tree nodes. You can
draw some simple instances on paper, which will make you totally clear about the thinking.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //105 class Solution { public: void travel(TreeNode **root) { if(*root){ travel(& ((*root) -> left)); cout<<"val is "<<(*root)->val<<endl; travel(& ((*root) -> right)); } } TreeNode* createTree(vector<int>& preorder, vector<int>& inorder, int preSta, int preEnd, int inSta, int inEnd) { if(preSta > preEnd || inSta > inEnd ) return NULL; TreeNode *root = new TreeNode(preorder[preSta]); int index; for(int i = inSta; i <= inEnd; i ++){ if(inorder[i] == preorder[preSta]){ index = i; break; } } root -> left = createTree(preorder, inorder, preSta + 1, preSta + index - inSta, inSta, index - 1); root -> right = createTree(preorder, inorder, preSta + index - inSta + 1, preEnd, index + 1, inEnd); return root; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { TreeNode *root = createTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1); TreeNode **r = &root; //travel(r); return root; } }; //106. class Solution { public: TreeNode* createTree(vector<int>& inorder, vector<int>& postorder, int inSta, int inEnd, int postSta, int postEnd){ if(inSta > inEnd || postSta > postEnd) return NULL; TreeNode* root = new TreeNode(postorder[postEnd]); int index; for(int i = inEnd; i >= inSta; i --){ if(postorder[postEnd] == inorder[i]){ index = i; break; } } root -> right = createTree(inorder, postorder, index + 1, inEnd, postEnd - (inEnd - index), postEnd - 1); root -> left = createTree(inorder, postorder, inSta, index - 1, postSta, postSta + (index - inSta - 1)); return root; } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { TreeNode* root = createTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); return root; } };