前序:根左右
中序:左根右
後序:左右根
前序遍歷:124563
中序遍歷:546213
後序遍歷:564231
package
datastructure
;public
class
binarytreedemo
}class
binarytree
public
binarytree
(hero root)
public
void
preorder()
public
void
midorder()
public
void
postorder()
}class
hero
public
hero
(int id,
string name)
@override
public
string
tostring()
';}// 前序遍歷:根左右
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);
}}
查詢及刪除
package
datastructure
;public
class
binarytreedemo
}class
binarytree
public
binarytree
(hero root)
public
void
preorder()
public
void
midorder()
public
void
postorder()
public
hero
preordersearch
(int id)
public
hero
midordersearch
(int id)
public
hero
postordersearch
(int id)
public
void
deletenode
(int id)
else
}else}}
class
hero
public
hero
(int id,
string name)
@override
public
string
tostring()
';}// 前序遍歷:根左右
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);
}// 前序遍歷查詢
public
hero
preordersearch
(int id)
hero hero =
null;if
(this
.left !=
null)if
(hero !=
null)if
(this
.right !=
null
)return hero;
}// 中序遍歷查詢
public
hero
midordersearch
(int id)
if(hero !=
null
)system
.out.
println
("中序查詢並比較");
if(this
.id == id)if(
this
.right !=
null
)return hero;
}// 後序遍歷查詢
public
hero
postordersearch
(int id)
if(hero !=
null)if
(this
.right !=
null)if
(hero !=
null
)system
.out.
println
("後序查詢並比較");
if(this
.id == id)
return
null;}
// 刪除結點(結點以下的子樹全部刪除)
// 先查詢左子樹,再查詢右子樹
// 重點是查詢當前結點的下乙個結點是否符合刪除條件。
public
boolean
deletenode
(int id)if(
this
.right !=
null
&&this
.right.id == id)
boolean flag =
false;if
(this
.left !=
null)}
if(this
.right !=
null
)return flag;
}}
二叉樹的前中後序遍歷
秋招記錄 對一棵二叉樹進行遍歷,我們可以採取3種順序進行遍歷,分別是前序遍歷 中序遍歷和後序遍歷。這三種方式是以訪問父節點的順序來進行命名的。假設父節點是n,左節點是l,右節點是r,那麼對應的訪問遍歷順序如下 前序遍歷 中左右 n l r 中序遍歷 左中右 l n r 後序遍歷 左右中 l r n ...
二叉樹的前 中 後序遍歷
import lombok.data import lombok.noargsconstructor data noargsconstructor class treenode 前序遍歷 根 左 右 public void preorder 遞迴向右子樹前序遍歷if this right null ...
二叉樹的前中後序遍歷
關於二叉樹的遍歷,常見的有三種遍歷方式,即,前序遍歷,中序遍歷,後序遍歷,這個 序 字,即指當前的節點對於其左右子節點的先後處理關係。結合我們剛剛講的,就知道對於其左右子樹而言,優先遍歷當前的父節點,然後遍歷它的左子樹,最後遍歷它的右子樹。對於其左右子樹而言,當前父節點在中間遍歷,即先遍歷當前節點的...