首页 > 其他 > 详细

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

时间:2016-01-08 13:05:11      阅读:204      评论:0      收藏:0      [点我收藏+]

题目: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;
    }
};

 

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

原文:http://www.cnblogs.com/CheeseZH/p/5112653.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!