模擬資料結構 二叉樹

2021-10-03 22:15:02 字數 3480 閱讀 7519

package com.zc.study;

/** * @author zc

* 二叉樹模擬

* 包含了:二叉樹的增刪改查功能

*/public

class

binarytreedemo

}/**

* 英雄類

*/class

hero

public

intgetid()

public

void

setid

(int id)

public string getname()

public

void

setname

(string name)

public hero getleft()

public

void

setleft

(hero left)

public hero getright()

public

void

setright

(hero right)

/** * 前序遍歷

* 步驟:先輸出根節點,然後輸出左節點、最後輸出右節點,按層數輸出

*/public

void

preorder()

//遞迴遍歷右節點if(

this

.right != null)

}/**

* 中序遍歷

* 步驟:先輸出左節點,然後輸出根節點、最後輸出右節點,按層數輸出

*/public

void

midorder()

//輸出根節點

system.out.

println

(this);

//輸出右節點if(

this

.right != null)

}/**

* 後序遍歷

* 步驟:先輸出左節點,然後輸出右節點、最後輸出根節點,按層數輸出

*/public

void

postorder()

//輸出右節點if(

this

.right != null)

//輸出根節點

system.out.

println

(this);

}/**

* 前序查詢:先根節點,再左節點,最後右節點

* @return

*/public hero findprebyid

(int id)

hero result = null;

//再左節點:遍歷左節點if(

this

.left != null)

//假設左節點找到了,就返回

if(result != null)

//最後右節點if(

this

.right != null)

//無論右節點是否找到,都返回

return result;

}/**

* 中序查詢:左節點 --> 根節點 --> 右節點

* @return

*/public hero findmid

(int id)

if(result != null)

//根節點if(

this

.id == id)

//右節點if(

this

.right != null)

//無論右節點是否找到,都要返回

return result;

}/**

* 後序查詢;左節點 --> 右節點 --> 根節點

* @return

*/public hero findpost

(int id)

if(result != null)

//右節點if(

this

.right != null)

//根節點if(

this

.id == id)

//無論右節點是否找到,都要返回

return result;

}/**

* 刪除節點

* 規定:如果刪除的是葉子節點,則直接刪除該節點;如果刪除的是非葉子節點,則直接刪除該子樹

* 步驟:先判斷當前節點的左節點,再判斷它的右節點,如果都不是,則繼續遞迴迴圈該操作

* 如果刪除的是根節點,則直接將根節點的指標指向null即可,根節點的刪除的在二叉樹類中完成

* @return

*/public

void

deletenode

(int id)

//清空右節點:判斷右節點是否是要刪除的節點if(

this

.right != null &&

this

.right.id == id)

//繼續從當前節點的左節點遞迴if(

this

.left != null)

//繼續從當前節點的右節點遞迴if(

this

.right != null)

}@override

public string tostring()

}/**

* 二叉樹類

*/class

binarytree

/** * 前序遍歷

*/public

void

preorder()

else

}/**

* 中序遍歷

*/public

void

midorder()

else

}/**

* 後序遍歷

*/public

void

postorder()

else

}/**

* 前序查詢

*/public hero prefind

(int id)

return result;

}/**

* 中序查詢

*/public hero midfind

(int id)

return result;

}/**

* 後序查詢

*/public hero postfind

(int id)

return result;

}/**

* 刪除節點

*/public

void

deletenode

(int id)

//清空根節點的指標並終止**執行

if(root != null && root.

getid()

== id)

//如果刪除的不是根節點,則繼續向下尋找

root.

deletenode

(id);}

}

資料結構 二叉樹 反轉二叉樹

include using namespace std define maxsize 1000 struct binary tree node class queue queue queue void queue push binary tree node btn binary tree node ...

《資料結構》 二叉樹

二叉樹 是 n個結點的有限集,它或為空集,或由乙個根結點及兩棵互不相交的 分別稱為該根的左子樹和右子樹的二叉樹組成。二叉樹不是樹的特殊情況,這是兩種不同的資料結構 它與無序樹和度為 2的有序樹不同。二叉樹的性質 1 二叉樹第 i層上的結點數最多為 2 i 1 2 深度為 k的二叉樹至多有 2 k 1...

資料結構 二叉樹

1.二叉樹 二叉樹是一種特殊結構的樹,每個節點中最多有兩個子節點,如圖1所示 圖1 二叉樹 在圖1中的二叉樹裡,a c有兩個子節點,b d有乙個子節點。對於二叉樹還有圖2中的以下情況 圖2 二叉樹的特殊情況 在博文中還介紹了滿二叉樹和完全二叉樹還有其他的特殊二叉樹。2.二叉樹的實現 有兩種實現方式,...