简体   繁体   中英

What is the sum of binary tree with given root and target nodes?

I have a binary tree as a function input I have tree root and 2 nodes I need to calculate the sum along the path between the two given nodes.

A tree example:

     4
   /   \
  8    13
 / \
24 45

Code:

List<Node> findPath(root, target):
if (root !=null)
    return
if root == node{
    return nodes.add(target)
}
path = findPath(root.left, target)
if (path !=null){
    return nodes.add(root).addAll(path)
}
path = findPath(root.right, target)
if (path!=null)
      return nodes.add(root).addAll(path)

I don't know what is the next step if I have paths to target nodes how should I calculate optimal way?

Input: sumTree(4, 24, 45)
Output: 8 + 24 + 45 = 77

Input: sumTree(4, 24, 13)
Output: 13 + 4 + 8 + 24 = 49

Input: sumTree(4, 4, 13)
Output: 4 + 13 = 17

Input: sumTree(4, 45, 45)
Output: 45

Language is JAVA but language doesn't matter unless I understand the syntax I just want to have optimal solution. Is it possible to provide some pseudocode?

Your two paths will have the same prefix (at least the root should be there). You need to remove the common prefix and add only the last (deepest) common node (once). For the parts that are different you need to add all the values. This should be O(N) complexity, and in-line with the rest of the solution.

Your search algorithm is not efficient because you keep copying the values from one list to the other ( O(N^2) if you don't have any constraints on the tree). If you modify it to build the response in place it should become O(N) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM