4.重建二叉树

题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
python:

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def reConstructBinaryTree(self, pre, tin):
        if len(pre) == 0 or len(tin) == 0:
            return None
        root = TreeNode(pre.pop(0))
        index = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre, tin[:index])
        root.right = self.reConstructBinaryTree(pre, tin[index + 1:])
        return root

c++

class Solution {
public:
    vector<int> my_copy(vector<int> a, int left, int right){
        // 区间拷贝(左闭右开)
        return vector<int> (a.begin()+left, a.begin()+right);
    }

    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        if(pre.size() == 0 || vin.size() == 0) return NULL;
        TreeNode *node = new TreeNode(pre[0]);
        for(int i=0; i < vin.size(); i++){
            // i 为根节点在中序遍历序列中的位置
            if(pre[0] == vin[i]){
                // 前序遍历
                node->left = reConstructBinaryTree(my_copy(pre,1,i+1),my_copy(vin, 0, i));
                node->right = reConstructBinaryTree(my_copy(pre,i+1, pre.size()), my_copy(vin, i+1, vin.size()));
            }
        }
        return node;
    }
};
发布了89 篇原创文章 · 获赞 0 · 访问量 1067

猜你喜欢

转载自blog.csdn.net/qq_26496077/article/details/103557768