Guest User

Untitled

a guest
Dec 1st, 2022
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.23 KB | None | 0 0
  1. class TreeDepthFirstSearch {
  2.  
  3.     class TreeNode(val data: Int, var left: TreeNode?, var right: TreeNode?)
  4.  
  5.  
  6.  
  7.     fun findPathsRecursive(root: TreeNode, sum: Int): MutableList<MutableList<Int>> {
  8.         var currentPath = mutableListOf<Int>()
  9.         var allPaths = mutableListOf<MutableList<Int>>()
  10.  
  11.          fun hasSumPath(
  12.             currentNode: TreeNode?,
  13.             sum: Int,
  14.             currentPath: MutableList<Int>,
  15.             allPaths: MutableList<MutableList<Int>>
  16.         ) {
  17.              if (currentNode == null) {
  18.                  return
  19.              }
  20.  
  21.              currentPath.add(currentNode.data)
  22.  
  23.              if (currentNode.data == sum && currentNode.left == null && currentNode.right == null) {
  24.                  allPaths.add(currentPath)
  25.              } else {
  26.                  hasSumPath(
  27.                      currentNode.left, sum - currentNode.data, currentPath, allPaths
  28.                  )
  29.                  hasSumPath(
  30.                      currentNode.right, sum - currentNode.data, currentPath, allPaths
  31.                  )
  32.              }
  33.              currentPath.removeAt(currentPath.size-1)
  34.          }
  35.  
  36.         hasSumPath(root, sum, currentPath, allPaths)
  37.         return allPaths
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment