[LeetCode By Go 86]257. Binary Tree Paths

題目

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

解題思路

使用遞歸解題,遞歸的過程中記錄當(dāng)前的路徑,找到葉子節(jié)點后將路徑放入結(jié)果數(shù)組中,在遞歸過程中:

  1. 如果左右子節(jié)點都為空指針,則說明當(dāng)前節(jié)點為二叉樹的葉子,獲得一條路徑,將這條路徑加入結(jié)果數(shù)組中
  2. 否則分別判斷左右子節(jié)點是否為空,如果不為空,則進行遞歸繼續(xù)尋找其路徑

代碼

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
var ret []string

func getPath(t *TreeNode, s string)  {
    val := t.Val
    s = s + "->" + strconv.Itoa(val)
    
    if nil == t.Left && nil == t.Right {
        ret = append(ret, s)
    }
    if nil != t.Left {
        getPath(t.Left, s)
    }
    if nil != t.Right {
        getPath(t.Right, s)
    }
}

func binaryTreePaths(root *TreeNode) []string {
    ret = []string{}
    if nil == root {
        return ret
    }

    rootval := root.Val
    
    if nil == root.Left && nil == root.Right {
        ret = append(ret, strconv.Itoa(rootval))
        return ret 
    } 
    if nil != root.Left {
        getPath(root.Left, strconv.Itoa(rootval))
    } 
    if nil != root.Right {
        getPath(root.Right, strconv.Itoa(rootval))
    }
    

    return ret
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容