您的位置:首页 > Web前端

牛客网-《剑指offer》-重建二叉树

2016-01-08 11:37 519 查看
题目:http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

C++

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
if (pre.size() == 0) {
return NULL;
}
TreeNode *root = new TreeNode(pre[0]);

vector<int> l_in, r_in, l_pre, r_pre;
bool flag = true;
for (int i = 0; i < pre.size(); i++) {
if (in[i] == pre[0]) {
flag = false;
continue;
}
if (flag == true) {
l_pre.push_back(pre[i+1]);
l_in.push_back(in[i]);
} else {
r_pre.push_back(pre[i]);
r_in.push_back(in[i]);;
}
}

root->left = reConstructBinaryTree(l_pre, l_in);
root->right = reConstructBinaryTree(r_pre, r_in);
return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: