Kotlin 鏈式存儲的二叉樹中查找節點

1. 查找方法

鏈式存儲的二叉樹中查找節點的方法可分爲三種:前序查找、中序查找、後序查找,下面使用 Kotlin 語言編碼實現查找函數,已建立的樹結構、節點權以下圖所示:node

1.1 前序查找函數
/**
     * 前序查找
     * */
    fun frontSearch(index: Int):TreeNode?{
        var node:TreeNode? = null

        if(index == this.value){
            return this
        }else{
            node = leftNode?.frontSearch(index)

            return node?:null

            node = rightNode?.frontSearch(index)
        }

        return node
    }

複製代碼
1.2 中序查找函數
/**
     * 中序查找
     * */
    fun middleSearch(index: Int): TreeNode? {
        var node:TreeNode? = null

        node = leftNode?.frontSearch(index)

        return node?:null

        if(index == this.value){
            return this
        }

        node = rightNode?.frontSearch(index)

        return node
    }

複製代碼
1.3 後序查找函數
/**
     * 後序查找
     * */
    fun afterSearch(index: Int): TreeNode? {
        var node:TreeNode? = null

        node = leftNode?.frontSearch(index)

        return node?:null

        node = rightNode?.frontSearch(index)

        return node?:null

        if(index == this.value){
            return this
        }

        return node
    }

複製代碼

2. 函數運行結果


本篇到此完結,若有補充內容隨時更新!歡迎關注本人繼續跟進技術乾貨的更新!bash

相關文章
相關標籤/搜索