二叉樹是一種非線性的資料結構,在對它進行操作時,總是需要逐一對每個資料元素實施操作,這樣就存在乙個操作順序問題,由此提出了二叉樹的遍歷操作。所謂遍歷二叉樹就是按某種順序訪問二叉樹中的每個結點一次且僅一次的過程。這裡的訪問可以是輸出、比較、更新、檢視元素內容等等各種操作。
在這裡寫了個二叉樹遍歷演算法、根據三種不同的順序得到三種不同的順序結果、
public class binarytreepublic void insert(binarytree root,int data)
break;
case 2://中序
if(root!=null)
break;
case 3://後序
if(root!=null)
break;
default:
break;
} }
public static void main(string args) ;
binarytree root = new binarytree(ints[0]); //建立二叉樹
for(int i=1;i
列印結果如下:
先序遍歷:
1 --> 22 --> 3 --> 5 --> 7 --> 9 --> 11 --> 44 --> 66 --> 88 -->
中序遍歷:
1 --> 3 --> 5 --> 7 --> 9 --> 11 --> 22 --> 44 --> 66 --> 88 -->
後序遍歷:
11 --> 9 --> 7 --> 5 --> 3 --> 88 --> 66 --> 44 --> 22 --> 1 -->
廣度遍歷二叉樹和深度遍歷二叉樹演算法
二叉樹演算法基本和遞迴有關,前中後序演算法就不提了,主要看一下深度優先遍歷和廣度優先遍歷。實現這2種遍歷需要借助棧或者佇列來儲存中間結果,原因是遍歷過程出現了回溯。1 筆試題 廣度遍歷二叉樹 深度遍歷二叉樹 23 include4 include5 include6 7using namespace...
構建二叉樹 遍歷二叉樹
陣列法構建二叉樹 public class main public static void main string args 用陣列的方式構建二叉樹 public static void createbintree 把linkedlist集合轉成二叉樹的形式 for int j 0 j 最後乙個父節...
二叉樹幾種遍歷演算法
二叉樹的遍歷 include include include using namespace std typedef struct node bintree typedef struct node1 btnode void creatbintree1 bintree root 前序遍歷建立樹,形如 ...