剑指Offer - 重建二叉树 (C/C++, Java, Python 2.x 实现)

 

题目描述

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

 

思路:在中序中找前序的开始节点,然后递归左右两边

 

 

C/C++    运行时间:5ms    占用内存:736k

/**
 * 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() || pre.size()!=vin.size())
	        return NULL;
        vector<int> left_pre, right_pre, left_vin, right_vin; 
        TreeNode *node = new TreeNode(pre[0]); 
        int left_length = 0; 
        while(pre[0]!=vin[left_length] && left_length < pre.size()) 
            ++ left_length; 
        for(int i=0; i<left_length; i++)
        {
            left_pre.push_back(pre[i+1]); 
            left_vin.push_back(vin[i]); 
        }
        for(int i=left_length+1; i<pre.size(); i++)
        {
            right_pre.push_back(pre[i]);
            right_vin.push_back(vin[i]);
        }
        node->left = reConstructBinaryTree(left_pre, left_vin);
        node->right = reConstructBinaryTree(right_pre, right_vin);
        return node;
    }
};

 

/**
 * 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* creat(int preBeg, int preEnd, int vinBeg, int vinEnd, vector<int> pre, vector<int> vin)
    {
        TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
        node->left = NULL;
        node->right = NULL;
        int key = pre[preBeg], flag = 0;//flag为在vin中标记 key的下标位置
        node->val = key;
        for(int i=vinBeg; i<=vinEnd; ++i)
        {
            if(vin[i]==key)
            {
                flag = i;
                break;
            }
        }
        if(flag>vinBeg) node->left = creat(preBeg+1, preBeg+flag-vinBeg, vinBeg, flag-1, pre, vin);//递归左边
        if(flag<vinEnd) node->right = creat(preBeg+flag-vinBeg+1, preEnd, flag+1, vinEnd, pre, vin);//递归右边
        return node;
    }
    
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin)
    {
        int preEnd = pre.size()-1;
        int vinEnd = vin.size()-1;
        return creat(0, preEnd, 0, vinEnd, pre, vin);//函数调用
    }
};

 

Java    运行时间:305ms    占用内存:24496k

 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution
{
    public TreeNode creat(int preBeg, int preEnd, int vinBeg, int vinEnd, int [] pre, int [] vin)
    {
        int key = pre[preBeg], flag = 0;//flag为在vin中标记 key的下标位置
        
        TreeNode node = new TreeNode(key);
        node.left = null;
        node.right = null;
        for(int i=vinBeg; i<=vinEnd; ++i)
        {
            if(vin[i]==key)
            {
                flag = i;
                break;
            }
        }
        if(flag>vinBeg) node.left = creat(preBeg+1, preBeg+flag-vinBeg, vinBeg, flag-1, pre, vin);//递归左边
        if(flag<vinEnd) node.right = creat(preBeg+flag-vinBeg+1, preEnd, flag+1, vinEnd, pre, vin);//递归右边
        return node;
    }
    
    public TreeNode reConstructBinaryTree(int [] pre,int [] in)
    {
        return creat(0, pre.length-1, 0, in.length-1, pre, in);
    }
}

Python 2.x    运行时间:59ms    占用内存:5864k

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def creat(self,preBeg, preEnd, vinBeg, vinEnd, pre, vin):
        key = pre[preBeg]
        flag = 0    #flag为在vin中标记 key的下标位置
        
        node = TreeNode(key)
        node.left = None
        node.right = None
        for i in range(vinBeg, vinEnd+1):
            if vin[i]==key:
                flag = i
                break
        if flag>vinBeg:
            node.left = self.creat(preBeg+1, preBeg+flag-vinBeg, vinBeg, flag-1, pre, vin)#递归左边
        if flag<vinEnd:
            node.right = self.creat(preBeg+flag-vinBeg+1, preEnd, flag+1, vinEnd, pre, vin)#递归右边
        return node
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        return self.creat(0, len(pre)-1, 0, len(tin)-1, pre, tin)

Python有实现递归的简单方法,如下:    运行时间:66ms    占用内存:5724k

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def reConstructBinaryTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if inorder:
            id = inorder.index(preorder.pop(0))
            root = TreeNode(inorder[id])
            root.left = self.reConstructBinaryTree(preorder, inorder[:id])
            root.right = self.reConstructBinaryTree(preorder, inorder[id+1:])
            return root

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值