题目
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”]
解题思路
使用递归解题,递归的过程中记录当前的路径,找到叶子节点后将路径放入结果数组中,在递归过程中:
- 如果左右子节点都为空指针,则说明当前节点为二叉树的叶子,获得一条路径,将这条路径加入结果数组中
- 否则分别判断左右子节点是否为空,如果不为空,则进行递归继续寻找其路径
代码
/**
* 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
}