Android中Tree的使用:
Tree的简单实例:
01.创建Tree
data class TreeNode(var leftNode: TreeNode? = null,
var value: Int? = null,
var rightNode: TreeNode? = null) {
fun frontShow() {
leftNode?.frontShow()
rightNode?.frontShow()
}
fun midShow() {
leftNode?.midShow()
rightNode?.midShow()
}
fun afterShow() {
leftNode?.afterShow()
rightNode?.afterShow()
}
}
data class BinaryTree(var rootNode: TreeNode){
fun frontShow() {
rootNode.frontShow()
}
fun midShow() {
rootNode.midShow()
}
fun afterShow() {
rootNode.afterShow()
}
}
02.显示二叉树
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var leftNode = TreeNode(TreeNode(value = 4), 2, TreeNode(value = 5))
var rightNode = TreeNode(TreeNode(value = 6), 3, TreeNode(value = 7))
var rootNode = TreeNode(leftNode = leftNode, value = 1, rightNode = rightNode)
var tree = BinaryTree(rootNode = rootNode)
tree.frontShow()
println("tree==$tree")
tree.midShow()
println("tree==$tree")
tree.afterShow()
println("tree==$tree")
}
}
Tree的拓展实例:
01.二叉树的遍历
class BinaryTree {
var root: TreeNode? = null
fun insert(value: Int) {
val newNode = TreeNode(value = value)
when(root) {
null -> root = newNode
else -> {
var currentNode: TreeNode? = root
var parentNode: TreeNode
while (true) {
parentNode = currentNode!!
when {
newNode.value!! > currentNode.value!! -> {
currentNode = currentNode.rightNode
if(currentNode == null) {
parentNode.rightNode = newNode
return
}
}
else -> {
currentNode = currentNode.leftNode
if(currentNode == null) {
parentNode.leftNode = newNode
return
}
}
}
}
}
}
}
fun inOrderDepth(treeNode: TreeNode?) {
if(treeNode != null) {
Log.i("前序遍历", "前序遍历:${treeNode.value.toString()}")
inOrderDepth(treeNode.leftNode)
Log.i("中序遍历","中序遍历:${treeNode.value.toString()}")
inOrderDepth(treeNode.rightNode)
Log.i("后序遍历", "后序遍历:${treeNode}")
}
}
fun inOrderWidth(treeNode: TreeNode?) {
if(treeNode == null) return
val nodelist = ArrayList<TreeNode>()
nodelist.add(treeNode)
while (nodelist.size > 0) {
val rnode = nodelist[0]
nodelist.remove(rnode)
Log.i("广度遍历", "广度遍历:${rnode.value.toString()}")
rnode.leftNode?.let { nodelist.add(it) }
rnode.rightNode?.let { nodelist.add(it) }
}
}
}
02.创建二叉树
binaryTree = BinaryTree()
binaryTree?.insert(10)
binaryTree?.insert(3)
binaryTree?.insert(5)
binaryTree?.insert(6)
binaryTree?.insert(7)
Log.i("遍历", "binaryTree==$binaryTree")
binaryTree?.inOrderDepth(binaryTree!!.root)
|