标签:|| 递归遍历 package pac tor xor Fix rgs length
用树的结构遍历数组
package com.atguigu.datastructures.binarytree
object ArrayTreeDemo {
def main(args: Array[String]): Unit = {
val arr = Array(1,2,3,4,5,6,7)
val arrayTree = new ArrayTree(arr)
arrayTree.postOrder()
}
}
class ArrayTree(val arr:Array[Int]){
//重载
def preOrder(): Unit ={
this.preOrder(0)
}
def infixOrder(): Unit ={
this.infixOrder(0)
}
def postOrder(): Unit ={
this.postOrder(0)
}
def preOrder(index:Int): Unit ={
if (arr == null || arr.length == 0){
println("数组为空,不能按照二叉树前序遍历")
}
println(arr(index))
//向左递归遍历
if ((index*2 + 1) < arr.length){
preOrder(index*2 + 1)
}
//向右递归遍历
if ((index*2 + 2) < arr.length){
preOrder(index*2 + 2)
}
}
def infixOrder(index:Int): Unit ={
if (arr == null || arr.length == 0){
println("数组为空,不能按照二叉树前序遍历")
}
//向左递归遍历
if ((index*2 + 1) < arr.length){
infixOrder(index*2 + 1)
}
println(arr(index))
//向右递归遍历
if ((index*2 + 2) < arr.length){
infixOrder(index*2 + 2)
}
}
def postOrder(index:Int): Unit ={
if (arr == null || arr.length == 0){
println("数组为空,不能按照二叉树前序遍历")
}
//向左递归遍历
if ((index*2 + 1) < arr.length){
postOrder(index*2 + 1)
}
//向右递归遍历
if ((index*2 + 2) < arr.length){
postOrder(index*2 + 2)
}
println(arr(index))
}
}
标签:|| 递归遍历 package pac tor xor Fix rgs length
原文地址:https://www.cnblogs.com/help-silence/p/13038582.html