package datastructure.tree
class Node[A] {
private var _data: A = _
def data: A = _data
def data_=(value: A): Unit = {
_data = value
}
private var _left: Node[A] = _
def left: Node[A] = _left
def left_=(value: Node[A]): Unit = {
_left = value
}
private var _right: Node[A] = _
def right: Node[A] = _right
def right_=(value: Node[A]): Unit = {
_right = value
}
def this(data: A) = {
this
this.data = data
}
override def toString: String = data.toString
/**
* 前序遍历
*/
def preOrder(): Unit = {
println(this) //输出父节点
//递归向左前序遍历
if (this.left != null) {
this.left.preOrder()
}
//递归向右前序遍历
if (this.right != null) {
this.right.preOrder()
}
}
/**
* 中序
*/
def midOrder(): Unit = {
//递归向左中序遍历
if (this.left != null) {
this.left.midOrder()
}
//输出父节点
println(this)
//递归向右中序遍历
if (this.right != null) {
this.right.midOrder()
}
}
/**
* 后序
*/
def postOrder(): Unit = {
//递归向左中序遍历
if (this.left != null) {
this.left.postOrder()
}
//递归向右中序遍历
if (this.right != null) {
this.right.postOrder()
}
//输出父节点
println(this)
}
}
class BinaryTree[A] {
private var _root: Node[A] = _
def root: Node[A] = _root
def root_=(value: Node[A]): Unit = {
_root = value
}
//前序
def preOrder(): Unit = {
if (root != null) {
root.preOrder()
} else {
println("树为空,无法遍历")
}
}
//中序
def midOrder(): Unit = {
if (root != null) {
root.midOrder()
} else {
println("树为空,无法遍历")
}
}
//后序
def postOrder(): Unit = {
if (root != null) {
root.postOrder()
} else {
println("树为空,无法遍历")
}
}
}
case class Hero(no: Int, name: String)
object BinaryTreeTest {
def main(args: Array[String]): Unit = {
//创建一棵二叉树
val tree = new BinaryTree[Hero]()
val hero1 = Hero(1, "宋江")
val hero2 = Hero(2, "吴用")
val hero3 = Hero(3, "卢俊义")
val hero4 = Hero(4, "林冲")
val hero5 = Hero(5, "关胜")
val root = new Node[Hero](hero1)
val node2 = new Node[Hero](hero2)
val node3 = new Node[Hero](hero3)
val node4 = new Node[Hero](hero4)
val node5 = new Node[Hero](hero5)
//说明 先手动创建二叉树,学习递归方式创建二叉树
root.left = node2
root.right = node3
node3.right = node4
node3.left = node5
tree.root = root
//测试前序遍历
println("前序")
tree.preOrder()
println("中序")
tree.midOrder()
println("后序")
tree.postOrder()
}
}
二叉树的前序中序后序遍历
最新推荐文章于 2024-10-17 09:50:44 发布