劍指Offer(面試題6 7)

2021-07-24 08:33:22 字數 1485 閱讀 7506

面試題6:重建二叉樹

題目:輸入某二叉樹的前序和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。假如輸入前序遍歷序列和中序遍歷序列。二叉樹結點的定義如下:

struct binarytreenode

;

我們可以寫出如下的遞迴**根據前序和中序遍歷的順序確定二叉樹結構:

binarytreenode* construct(int* preorder,int* inorder,int

length)

binarytreenode* constructcore

( int* startpreorder,int* endpreorder,

int* startinorder,int

*endinorder)

//在中序遍歷中找到根結點的值

int* rootinorder = startinorder;

while(rootinorder<=endinorder && *rootinorder != rootvalue)

++rootinorder;

if(rootinorder == endinorder && *rootinorder != rootvalue)

throw std::exception("invalid input.");

int leftlength=rootinorder-startinorder;

int* leftpreorderend = startpreorder+leftlength;

if(leftlength>0)

if(leftlength//構建右子樹

root->m_pright = constructcore(leftpreorderend+1,endpreorder,rootinorder+1,endinorder);

}return root;

}

在函式constructcore中,我們先根據前序遍歷序列的第乙個數字建立根結點,接下來在中序遍歷序列中找到根結點的位置,這樣就能確定左、右子樹結點的數量。在前序遍歷和中序遍歷的序列中劃分了左、右子樹結點的值之後,我們就可以遞迴地呼叫函式constructcore,去分別構建它的左右子樹。

面試題7:用兩個棧實現佇列

template

class cqueue

template

template

t cqueue::deletehead()

}if(stack2.size()==0)

throw

new exception("queue is empty");

t head = stack2.top();

stack2.pop();

return head;

}

參考書籍《劍指offer》

劍指offer面試題7

面試題7 用兩個棧實現佇列 using namespace std template class cqueue 預備知識 佇列 佇列也是一種常見的資料結構 特點是先進先出 fifo 在stl中有stack和queue兩個容器 template class stack 成員函式 empty size ...

劍指offer面試題11

面試題1 數值的整數的次方 題目 實現函式double power double base,int exponent 求base的 exponent次方。不得使用庫函式,同時不需要考慮大數問題。思路 首先應該明確指數的可能取值 正整數,0,負整數 另外還需要考慮底數是0的情形。對於負整指數,我們可以...

劍指offer面試題15

面試題15 鍊錶中倒數第k個結點 題目 輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。為了符合大多數人的習慣,本題從1開始計數,即鍊錶的尾結點是倒數第乙個結點。例如乙個鍊錶有6個結點,從頭結點開始它們的值依次是1 2 3 4 5 6。這個鍊錶的倒數第3個結點是值為4的結點。預備知識 鍊錶結點的定義如下 ...