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() 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)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)