Construct Binary Tree from Inorder and Postorder Traversal
OJ: https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
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 binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ TreeNode *createTree(vector<int> &inorder, int start, int end, vector<int> &postorder, int start2, int end2) { if(start > end || start2 > end2) return NULL; TreeNode *root = new TreeNode(postorder[end2]); int i; for(i = start; i <= end; ++i) if(inorder[i] == postorder[end2]) break; // if(i > end) throws std::exception("error"); root->left = createTree(inorder, start, i-1, postorder, start2, start2 + i-start-1); root->right = createTree(inorder, i+1, end, postorder, start2+i-start, end2-1); return root; } class Solution { public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { return createTree(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1); } };
Construct Binary Tree from Preorder and Inorder Traversal
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) {} * }; */ TreeNode* createTree(vector<int> &preorder, int start, int end, vector<int> &inorder, int start2, int end2) { if(start > end || start2 > end2) return NULL; TreeNode *root = new TreeNode(preorder[start]); int i; for(i = start2; i <= end2; ++i) if(preorder[start] == inorder[i]) break; root->left = createTree(preorder, start+1, start+i-start2, inorder, start2, i-1); root->right = createTree(preorder, start+i-start2+1, end, inorder, i+1, end2); return root; } class Solution { public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { return createTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1); } };