本文主要是介绍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 a binary tree node.* 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 i = 0;return build(preorder, inorder, i, 0, preorder.size() - 1);}TreeNode* build(vector<int>& preorder, vector<int>& inorder,int& i,int start,int end) {TreeNode* left = NULL;TreeNode* right = NULL;for (int j = start; j <= end; j++){if (inorder[j] == preorder[i]){left = build(preorder, inorder, ++i, start, j - 1);right = build(preorder, inorder, i, j + 1, end);TreeNode* tree = new TreeNode(inorder[j]);tree->left = left;tree->right = right;return tree;}}return NULL;}
};
这篇关于Construct Binary Tree from Preorder and Inorder Traversal问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!