注:主要是指二叉樹 d是指根節點,l是左節點,r是右節點
前序遍歷
drl (先取根節點,再取左節點,最後取右節點)
結果:
public
void
frontshow()
if(this
.treerightnode!=null)
}
中序遍歷
ldr(先取左節點,再取根點,最後取右節點)
結果:
public
void
midshow()
system.out.
print
(this
.getvalue()
+"\t");
if(this
.treerightnode!=null)
}
後序遍歷
lrd(先取左節點,再取右節點,最後取根節點)
結果:
public
void
finalshow()
if(this
.treerightnode != null)
system.out.
print
(this
.getvalue()
+"\t");
}
注:每到乙個新的節點,就要用遍歷的思想進行判斷取哪個節點,這可以用遞迴的思想處理前序查詢
public treenode frontsearch
(int i)
else
//如果左節點找到了就不用遍歷右節點
if(target != null)
//查詢右節點if(
this
.treerightnode != null)
}return target;
}
中序查詢
//中序查詢
public treenode midsearch
(int i)
if(target != null)if(
this
.getvalue()
== i)
else
return target;
}}
後序查詢//後續查詢
public treenode aftersearch
(int i)
if(target!=null)if(
this
.treerightnode!=null)if(
this
.getvalue()
==i)
return target;
}
資料結構 樹的遍歷
以前序遍歷為例 1 先遍歷樹根 2 然後前序遍歷左子樹 3 最後前序遍歷右子樹 對於這樣的乙個二叉樹 前序遍歷結果 abdegcf 遍歷流程 首先遍歷樹根,輸出a 對a的左子樹進行前序遍歷,怎麼前序遍歷?對於b這個左子樹而言,首先遍歷根節點,輸出b 然後遍歷子樹b的左子樹,得到d這個子樹,對d進行前...
資料結構 樹的遍歷(遞迴遍歷)
樹的遍歷 遞迴遍歷 include include include typedef struct treenodetreenode,treenodepointer 先序遍歷 void printroot treenodepointer root 中序遍歷 void printroot2 treeno...
資料結構學習之 樹的遍歷
今天學習的是資料結構有關樹的遍歷的知識點。以下將會講到樹的幾種基本的的遍歷方式,以及通過例題來鞏固知識點。二叉樹的遍歷是指通過一定順序訪問二叉樹的所有結點。一般有四種方法 先序遍歷 中序遍歷 後序遍歷 層序遍歷。前三種一般使用深度優先搜尋dfs實現,而層序遍歷一般使用廣度優先搜尋bfs來實現。首先給...