剑指offer66题--Java实现,c++实现和python实现 4.重建二叉树

题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
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:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        
        if(pre.empty()||vin.empty())//递归出口
            return nullptr;

        TreeNode  *head = new TreeNode(pre[0]); //创建根节点
        int root=0;
        for(int i=0;i<vin.size();++i)//遍历中序遍历序列
        {
            if(vin[i]==pre[0])//如果vin[i]等于根节点
            {
                root=i;//则i为中序遍历中根节点的索引
                break;
            }
        }
        //先序和中序的左右子树vector
        vector<int> preleft,preright,vinleft,vinright;
        for(int i=0;i<root;++i)
        {
            preleft.push_back(pre[i+1]);
            vinleft.push_back(vin[i]);
        }
        for(int i=root+1;i<pre.size();++i)
        {
            preright.push_back(pre[i]);
            vinright.push_back(vin[i]);
        }
        //根节点的左右节点
        head->left=reConstructBinaryTree(preleft,vinleft);
        head->right=reConstructBinaryTree(preright,vinright);
        
        return head;
    }
};

Java实现

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.Arrays;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre.length==0||in.length==0)
            return null;
        TreeNode node=new TreeNode(pre[0]);
        for(int i=0;i<in.length;i++)
        {
            if(in[i]==pre[0])
            {
                node.left=reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i+1),Arrays.copyOfRange(in, 0,i));
                node.right=reConstructBinaryTree(Arrays.copyOfRange(pre, i+1, pre.length),Arrays.copyOfRange(in, i+1, in.length));
            }
        }
        return node;
    }
}

python实现

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):#self指的是类实例对象本身
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        if len(pre)==0:
            return None
        if len(pre)==1:
            return TreeNode(pre[0])
        else:
            flag=TreeNode(pre[0])
            flag.left=self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])])#Python index() 从列表中找出某个值第一个匹配项的索引位置
            flag.right=self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tin[tin.index(pre[0])+1:])
        return flag;
        # write code here

猜你喜欢

转载自blog.csdn.net/walter7/article/details/84245641