leetcode之Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:通用数据采集软件 编辑:程序博客网 时间:2024/05/13 05:20


题目:

Given preorder and inorder traversal of a tree, construct the binary 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* maketree(vector<int>& preorder, vector<int>& inorder, int pstart, int pend, int instart, int inend) {if (pstart > pend || instart > inend) return NULL;TreeNode* a = new TreeNode(preorder[pstart]);if (pstart == pend&&instart == inend) return a;int location;for (int i = instart; i <= inend; i++) {if (inorder[i] == preorder[pstart]) {location = i;break;}}a->left = maketree(preorder, inorder, pstart + 1, location-instart+pstart, instart, location - 1);a->right = maketree(preorder, inorder, pstart+location-instart+1, pend, location + 1, inend);return a;}TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {if (preorder.empty()) return NULL;TreeNode* a = new TreeNode(preorder[0]);int location;for (int i = 0; i < inorder.size(); i++) {if (inorder[i] == preorder[0]) {location = i;break;}}a->left = maketree(preorder, inorder, 1, location, 0, location-1);a->right = maketree(preorder, inorder, location + 1, inorder.size() - 1, location + 1, inorder.size() - 1);return a;}};



0 0
原创粉丝点击