二叉樹是樹的一種特殊結構,也是一種極為重要的樹,二叉樹最重要的操作是遍歷,即按照一定的順序訪問樹中的所有節點,常見的遍歷方式有:
對遍歷來說,最容易想到的方式就是遞迴,遞迴**簡單,但是效率不高,需要的棧空間比較大,非遞迴的方法**較為複雜,不過效率較高。
遞迴實現:
非遞迴實現:void preordervisit(binarytreenode *pnode)
}
前序遍歷要求先訪問根節點,再訪問其左右節點,處理過程如下:
1)從根節點p開始,將p入棧;
2)訪問棧頂元素,並做出棧操作,若其右節點不為空,將右節點入棧;若左節點不為空,將左節點入棧;
3)重複第2步,直到棧為空;
**如下:
遞迴實現:void preordervisit_nonrecursively(binarytreenode *pnode)
if (ptemp->m_pleft)
}}
非遞迴實現:void inordervisit(binarytreenode *pnode)
}
處理過程如下:
1)從根節點p開始,將p入棧,若p的左節點不為空,則將左節點入棧,並令p = p->m_pleft,直到左節點為空;
2)訪問棧頂元素,做出棧處理,若其右節點不為空,將右節點入棧,並令當前指標等於右節點;
3)重複上述過程,直到棧為空;
**如下:
遞迴實現:void inordervisit_nonrecursively(binarytreenode * pnode)
ptemp = nodes.top();
nodes.pop();
printf("%d\t", ptemp->m_nvalue);
ptemp = ptemp->m_pright;
}
非遞迴實現:void posordertvisit(binarytreenode *pnode)
}
處理過程如下:
1)從根節點p開始,將p入棧;
2)取棧頂元素,若其左節點、右節點均為空,則可以直接訪問該元素;或者該節點的左右子節點都已訪問過,則也可以直接訪問該元素;若非上述兩種情況,則依次將右子節點、左子節點入棧;
3)重複第2步,直到棧為空;
**如下:
這裡是根據前序遍歷和中序遍歷來重建二叉樹,且假設遍歷結果中沒有重複的元素。void posordertvisit_nonrecursively(binarytreenode * pnode)
else
if (pcurrentnode->m_pleft)
}}}
遞迴實現:
int rebuildbinarytree(int *ppreorder, int *pinorder, int treelen, binarytreenode **proot)
else
}//劃分左右子樹
int i;
int built = 0;
int *prootinorder = pinorder;
//int *pendinorder = pinorder + treelen - 1;
/*while (prootinorder < pendinorder && *prootinorder != *ppreorder)
++ prootinorder;
if (prootinorder == pendinorder && *prootinorder != *ppreorder)
return 0;*/
for (i = 0; i < treelen; i++, prootinorder++)
}else if (leftlength && rightlength <= 0)
}else if (leftlength <= 0 && rightlength)
}} }
return built?1 : 0;
}
二叉樹學習筆記
1.訪問根節點 2.在訪問第 l 層時,將 l 1 層的節點按順序儲存到佇列中 3.進入下一層並訪問該層的所有節點 4.重複上述操作直到所有層都訪問完 時間複雜度 o n 空間複雜度o n 最壞的情況下,最後一層的所有節點可能在佇列中 void levelorder node root q.dele...
二叉樹學習筆記
二.遞迴解法 三.非遞迴解法 include using namespace std char ch typedef char elemtype typedef struct bitnodebitnode,bitree 先序序列存入 void createbitree bitree t 採用先序遍歷...
學習筆記 樹 二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。本題主要採用遞迴的思想。首先介紹一下根據前序遍歷和中序遍歷來構建二叉樹的思路 前序遍歷的第乙個則是二叉樹的根,找到根在中序遍歷中的位...