線索二叉樹的建立及其遍歷訪問操作

2021-07-30 15:19:41 字數 2158 閱讀 6522

對於線索二叉樹有先序、中序、後序三種,但是只有中序線索二叉樹才能獲得任意節點的前驅和後繼節點(實際上二叉樹任意節點的訪問均是訪問的某一棵樹的根節點),那麼只有中序遍歷生成的中序線索二叉樹是先訪問左子樹,根節點,右子樹,而先序線索二叉樹,是先訪問根節點,所以只能從先序線索二叉樹中得到節點的後繼結點,同理只能從後序線索二叉樹得到節點的前驅結點(最後訪問根節點)。

package ccnu.offer.tree;

public

class demo03 , new

int, 0, 0, 5);

threadnode inroot = createinthreadbitree(root);

inorder(inroot);

system.out.println();

inorderbyreverse(inroot);

}public

static threadnode createbitreebyprein(int pre, int in, int prebegin, int inbegin, int len)

if(len <= 0)

threadnode root = new threadnode(pre[prebegin]);

int rootindex;

for(rootindex = 0; in[rootindex] != pre[prebegin]; rootindex++);

root.lchild = createbitreebyprein(pre, in, prebegin + 1, inbegin, rootindex - inbegin);

root.rchild = createbitreebyprein(pre, in, prebegin + (rootindex - inbegin) + 1, rootindex + 1, len - (rootindex - inbegin) - 1);

return root;

}public

static threadnode createinthreadbitree(threadnode root)

return root;

}public

static

void

inthreadbitree(threadnode root)

if(pre != null && pre.rchild == null)

pre = root; // 將剛才訪問的節點儲存,注意訪問最後乙個節點時,pre會指向它

inthreadbitree(root.rchild); // 第三步:線索化當前root的右子樹}}

public

static

void

inorder(threadnode root)

threadnode firstnode = firstnode(root);

threadnode p = firstnode;

while(p != null)

}public

static

void

inorderbyreverse(threadnode root)

threadnode lastnode = lastnode(root);

threadnode p = lastnode;

while(p != null)

}public

static threadnode firstnode(threadnode root)

while(root.ltag == 0)

return root;

}public

static threadnode lastnode(threadnode root)

while(root.rtag == 0)

return root; //

}public

static threadnode previousnode(threadnode p)

if(p.ltag == 0)else

}public

static threadnode nextnode(threadnode p)

if(p.rtag == 0)else

}private

static

class threadnode

}}

樹 線索二叉樹的建立及其遍歷

0線索二叉樹的儲存結構體 1先序序列化 先序構樹思想 對於先序線索二叉樹,我想提醒的是 每次只會把當前節點的左子樹前驅鏈上,這一次的 後繼 不會在本次鏈上,當pcur指向下乙個節點的時候,才會把上一次的後繼鏈上 先序線索化 先序遍歷的思想 先往左遍歷一遍,到底了之後往後繼節點或者右子樹找 要先判斷是...

線索二叉樹建立及遍歷

層序輸入 中序遍歷建立線索二叉樹 利用頭節點遍歷線索二叉樹 include using namespace std typedef char elemtype define maxsize 100 enum tag 二叉鍊錶的結構建立 typedef struct bitnodebitnode,bi...

線索二叉樹遍歷

1.對二叉樹線索化之後,若結點沒有右子樹,則右子樹指向遍歷後繼結點 若沒有左子樹,則左子樹指向遍歷前驅結點。2.對線索二叉樹進行遍歷,即不斷找結點的後繼。若右指標直接指向了後繼,那直接就有了 結點右指標沒有指向後繼,即有右子節點,那就通過常規方法找到後繼。如後序線索樹後繼不好找,需要棧才能進行遍歷。...