根據前序和中序遍歷結果重建二叉樹

2021-07-31 17:30:45 字數 1568 閱讀 9124

前序遍歷:

根節點—->左子樹—->右子樹

中序遍歷:

左孩子—->根節點—->右子樹

根據前序遍歷的特性可以得知:

1.前序遍歷後的第乙個節點就是這棵樹的根節點。

2.根據中序遍歷找到根節點後,其左邊的節點都是根節點的左子樹,其右邊的節點都是根節點的右子樹。

3.用遞迴的方式將根節點的左子樹和右子樹分別看成是一棵樹。

對於遞迴出口,可以是:beginpre = endpre

beginpre:先序遍歷的第乙個節點的值

endpre:先序遍歷的最後乙個節點的值

beginin:中序遍歷的第乙個節點的值

endin:中序遍歷的最後乙個節點的值

可以將這四個值作為函式的引數列表來傳遞。

建立樹的結點:

#include 

#include

#include

using

namespace

std;

struct node

;

遞迴建立樹:

node* preandinorderbuilt(int arrpre, size_t beginpre,size_t endpre, int arrin, size_t beginin,size_t endin)

if(beginpre > endpre)

return null;

node* proot = (node*)malloc(sizeof(node));//建立根節點

proot->_value = arrpre[beginpre];

proot->_pleft = null;

proot->_pright = null;

if(beginpre == endpre)

return proot;

//在中序遍歷中找到跟結點的位置,區分開左子樹與右子樹

size_t index = beginin;

for(index; index

<=endin; index++)

if(index > endin)//兩個數的根節點不同

return null;

//建立左子樹

size_t newendpre = 0;

if(index > beginin)//左子樹存在

//建立右子樹

if(index

< endin)//右子樹存在

return proot;

}

呼叫:

根據前序遍歷和中序遍歷結果重建二叉樹(遞迴方法)

假設已經有了前序遍歷和中序遍歷的結果,如何重建這棵樹呢?給定函式定義如下 void rebuild char ppreorder,前序遍歷結果 char pinorder,中序遍歷結果 intntreelen,樹的長度 node proot 返回node 型別 用遞迴的方法解法如下 include ...

根據前序遍歷和中序遍歷的結果重建二叉樹

題目 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。為便於理解,重建出的二叉樹如下 python 如下 class treenode def init self,x self.v...

根據前序遍歷和中序遍歷重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。class treenode public class s2 public treenode reconstruct int pre...