博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
牛客网-《剑指offer》-重建二叉树
阅读量:6848 次
发布时间:2019-06-26

本文共 1092 字,大约阅读时间需要 3 分钟。

题目: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
pre,vector
in) { if (pre.size() == 0) { return NULL; } TreeNode *root = new TreeNode(pre[0]); vector
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; }};

 

转载地址:http://ibrul.baihongyu.com/

你可能感兴趣的文章