二叉樹的括號表示法 遍歷和列印

2021-10-09 05:17:21 字數 2645 閱讀 9351

給你乙個括號表示法表示的二叉樹,建立一棵用二叉鍊錶方式儲存的二叉樹,並利用凹凸法進行二叉樹的列印;並對其進行遍歷(先序、中序、後序和層序),並列印輸出遍歷結果。

輸入:a(b(c,d(e,f(g))))

輸出:先序遍歷:abcdefg

中序遍歷:cbedgfa

後序遍歷:cegfdba

層序遍歷:abcdefg

#pragma gcc optimize(3,"ofast","inline")

#include#include#include#include#include#include#include#include#include#include#include#include#include#include#include#include#include#define f(i,s,t) for(int i=(s);i<=(t);i++)

#define d(i,s,t) for(int i=(s);i>=(t);i--)

#define dbug(i) printf("value=%d\n",i)

#define ddbug(i,j) printf("value=%d %d\n",i,j)

#define ed putchar('\n')

#define fo freopen("d:\\in.txt","r",stdin)

#define ios cin.tie(0) ,cout.tie(0), cout.sync_with_stdio(0)

typedef long long ll;

//const int inf = 1 << 30;

//const double eps = 1e-6;

//#define mx 102

//#define mod 10000

using namespace std;

typedef struct nodebitree;

//構造二叉鍊錶

bitree* creatbitree(char str1)

//if

else//else

}//switch

strpoint++;

temp = str1[strpoint];

}//while

return root;

}/*先序遍歷二叉樹, root為指向二叉樹根結點的指標*/

void preorderrecursion(bitree *root)

//if

}/*中序遍歷二叉樹, root為指向二叉樹根結點的指標*/

void inorderrecursion(bitree *root)

//if

}/* 後序遍歷二叉樹,root為指向二叉樹(或某一子樹)根結點的指標*/

void postorderrecursion(bitree *root)

//if

}/* 先序遍歷二叉樹的非遞迴演算法 */

void preorder(bitree *root)

//inner whlie

if (!s.empty())//if

}//extren while

}/* 中序遍歷二叉樹的非遞迴演算法 */

void inorder(bitree *root)

//inner whlie

if (!s.empty())//if

}//extren while

}/* 後序遍歷二叉樹的非遞迴演算法 */

void postorder(bitree *root)

//if

else//if

else//else

}//extren else

}//while

}/* 層序遍歷二叉樹 */

void layerorder(bitree *root)

if (temp->rchild != null)

}//while

}void printtree(bitree *root, int nlayer)

printtree(root->rchild,nlayer + 3);

for (int i = 0; i < nlayer; i++)

printf("%c\n",root->data);

printtree(root->lchild, nlayer + 3);

}int main()

上面**實現了遞迴和非遞迴的遍歷。

非遞迴遍歷中,用棧來儲存結點,為了可以在遍歷它的孩子時,還可以通過棧找到孩子結點的父結點。

而後序非遞迴遍歷較前兩種遍歷方法比較難實現,原因在於需要遍歷完左子樹,遍歷完右子樹,最後才去訪問根節點。這樣棧頂結點可能會從他的左子樹返回,也有可能從他的右子樹返回,需要區分這種情況,如果是第一次從左子樹返回,那麼還需要去遍歷其右子樹,如果是從右子樹返回,那麼直接返回該結點就可以了。這裡使用輔助指標來區分**。

temp = s.top();

if (temp->rchild && temp->rchild != r)//if

else//else

好的!下篇實現moris遍歷!

非二叉樹轉二叉樹的表示法

樹的儲存結構,詳細 分析在 秦玉平 馬靖善所編的資料結構 第三版 p137 142 include define max 100 typedef char elemtype 雙親表示法 typedef structptnode typedef structptree 孩子雙親表示法,若需要孩子鍊錶表...

二叉樹的基本運算及實現(括號表示法)

部分 參考於 資料結構與演算法 二叉樹鏈式儲存與括號表示法的相互轉換 include include using namespace std struct treenode void createbtnode treenode root,char str p 棧st存放要操作的結點,p指向新節點 i...

二叉樹3 二叉樹按層遍歷列印

題目 有一棵二叉樹,請設計乙個演算法,按照層次列印這棵二叉樹。給定二叉樹的根結點root,請返回列印結果,結果按照每一層乙個陣列進行儲存,所有陣列的順序按照層數從上往下,且每一層的陣列內元素按照從左往右排列。保證結點數小於等於500。思路 對於二叉樹,除了先序遍歷 中序遍歷 後序遍歷之外,常用的遍歷...