Go语言实现:【剑指offer】二叉树中和为某一值的路径

该题目来源于牛客网《剑指offer》专题。

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

Go语言实现:

var arrAll [][]int
var arrPath []int

func findPath(root *TreeNode, target int) [][]int {
   if root == nil {
      return arrAll
   }
   arrPath = append(arrPath, root.Val)
   target -= root.Val
   //目标数减为0,且是叶子结点
   if target == 0 && root.Left == nil && root.Right == nil {
      //需拿到当前的arrPath
      arr := arrPath
      arrAll = append(arrAll, arr)
   }
   findPath(root.Left, target)
   findPath(root.Right, target)
   //比如二叉树{1,2,3},arrPath先{1,2},然后{1,3},所以arrPath需回退到上一位
   arrPath = append(arrPath[:len(arrPath)-1], arrPath[len(arrPath):]...)
   return arrAll
}

//冒泡排序
func bubbleSort(arrAll [][]int) [][]int {
   length := len(arrAll)
   for i := 0; i < length-1; i++ {
      for j := i + 1; j < length; j++ {
         if len(arrAll[i]) < len(arrAll[j]) {
            arrAll[i], arrAll[j] = arrAll[j], arrAll[i]
         }
      }
   }
   return arrAll
}
原文地址:https://www.cnblogs.com/dubinyang/p/12129932.html