leetcode 105. 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.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
思路还是比较简单的,在中序遍历中找前序遍历的值,然后递归
/**
* 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* dfs(vector<int>& preorder, vector<int>& inorder, int l, int r, int &num) {
TreeNode* root = new TreeNode(preorder[num]);
if (l > r) return nullptr;
int p = l;
while (p <= r && inorder[p] != preorder[num]) ++p;
++num;
root->left = dfs(preorder, inorder, l, p-1, num);
root->right = dfs(preorder, inorder, p+1, r, num);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int r = inorder.size() - 1;
if (r == -1) return nullptr;
int l = 0, num = 0;
return dfs(preorder, inorder, l, r, num);
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: