面試題7:重建二叉樹

lightmare625發表於2018-07-15

對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

相關文章