面试题7:重建二叉树

对vector使用指针

#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
	vector<int> a,b,c;
 
	for (int i = 0; i < 3; i++)
	{
		a.push_back( i );
		b.push_back( i  + 3);
		c.push_back(i + 6);
	}
	vector<int>* seq[3] = {&a,&b,&c};
	vector<int>* curr = 0;
	for (int j = 0; j < 3; j++)
	{
		curr = seq[j];
		printf("%d\n", curr->at(0) );
		printf("%d\n", curr->at(1));
		printf("%d\n", curr->at(2) );
	}
	getchar();}

 

二叉树结构体定义

 

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};




 

题目描述

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

 

刷第一遍

 

/**
 * 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) {
        int lenth = pre.size();
        //① 空树
        if(lenth == 0 || &pre == nullptr || &vin == nullptr)
            return nullptr;
        Core(&pre,&pre+lenth-1,&vin,&vin+lenth-1);
    }
    
    //S第一个数,E最后一个数
    TreeNode* Core(int* preS,int* preE,int* vinS,int* vinE)//bug1
    {
        //初试化根节点
        int rootvalue = preS->val;//bug2
        TreeNode* root = new TreeNode(rootvalue);
        
        //② 只有一个根节点
        if(preS == preE)
        {
            if(vinS == vinE && vinS->val == preS->val)
            {
                return root;
            }
            else
            {
                throw exception("wrong");
            }
        }
        
        //求leftlength
        //先找vinroot
        int* vinroot = preS;
        while(vinroot <= vinE && vinroot->val != rootvalue)//这里的二叉树一定不含重复数字不然就不能这样找vinroot了
            ++vinroot;
        
        //③ 如果vin中没有root,报错
        if(vinroot == vinE && vinroot->val != rootvalue )
            throw exception("wrong");
        
        int leftlength = vinroot - preS;
        
        //左子树
        root->left = Core(preS + 1,preS + leftlength ,vinS,vinroot - 1);
            
        //右子树
        root->right = Core(preS + leftlength + 1,preE,vinroor + 1,vinE);
            
        return root;
    }
};

 

1.

 

 

TreeNode* Core(int* preS,int* preE,int* vinS,int* vinE)//bug1

error: cannot initialize a parameter of type 'int *' with an rvalue of type 'vector *'

Core(&pre,&pre+lenth-1,&vin,&vin+lenth-1);

修改为

 TreeNode* Core(vector<int>* preS,vector<int>* preE,vector<int>* vinS,vector<int>* vinE)

2.

 

int rootvalue = preS->val;//bug2

error: no member named 'val' in 'std::vector<int, std::allocator >'
int rootvalue = preS->val;

vector<int>* 是对 vector 的指针,下一个是vector的下一位

 

刷第二遍

提交时间:2018-07-15 语言:C++ 运行时间: 5 ms 占用内存:612K 状态:答案正确

/**
 * 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) {
        int lenth = pre.size();
         
        //① 空树
        if(lenth <= 0 || &pre == nullptr || &vin == nullptr)
            return nullptr;
        return Core(&pre[0],&pre[0]+lenth-1,&vin[0],&vin[0]+lenth-1);
    }
     
    //S第一个数,E最后一个数
    TreeNode* Core(int* preS,int* preE,int* vinS,int* vinE)
    {
        //初试化根节点
        int rootvalue = *preS;
        TreeNode* root = new TreeNode(rootvalue);
         
        //② 只有一个根节点
        if(preS == preE)
        {
            if(vinS == vinE && *vinS == *preS)
            {
                return root;
            }
            else
            {
                throw exception();
            }
        }
         
        //求leftlength
        //先找vinroot
        int* vinroot = vinS;//bug1:int* vinroot = preS;
        while(vinroot <= vinE && *vinroot != rootvalue)//这里的二叉树一定不含重复数字不然就不能这样找vinroot了
            ++vinroot;
         
        //③ 如果vin中没有root,报错
        if(vinroot == vinE && *vinroot != rootvalue )
            throw exception();
         
        int leftlength = vinroot - vinS;//bug2:int leftlength = vinroot - preS;
         
        //左子树
        if(leftlength>0)//bug3忘了判断递归条件,不判断会内存超限
        root->left = Core(preS + 1,preS + leftlength ,vinS,vinroot - 1);
             
        //右子树
        if(preE-preS>leftlength)//bug3忘了判断递归条件
        root->right = Core(preS + leftlength + 1,preE,vinroot + 1,vinE);
             
        return root;
    }
};

 

优秀代码参考

 

public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
        return root;
    }
    
    private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {
        if(startPre>endPre||startIn>endIn)
            return null;
        TreeNode root=new TreeNode(pre[startPre]); 
        for(int i=startIn;i<=endIn;i++)
            if(in[i]==pre[startPre]){
                root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
                root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
                      break;
            }   
        return root;
    }
}

数组的索引与指针的思想。

 

Python 

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if not pre or not tin:
            return None
        root = TreeNode(pre.pop(0))
        index = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre, tin[:index])   //(pre[:index], tin[:index])        
        root.right = self.reConstructBinaryTree(pre, tin[index + 1:])//(pre[index:], tin[index+1:]) 
        return root

python 切片[1:5] 输出索引1~4

posted @ 2018-07-15 23:09  lightmare  阅读(125)  评论(0编辑  收藏  举报