-1

Give a recursive algorithm btProd which takes as input a binary tree, and outputs the value that is the product of the numbers contained in the binary tree. If the input is the null tree, then the algorithm should return null.

Algorithm btProd(P)

Require: Input is a tree P

1: btProd(null) ← 0

2: btProd(leaf x) ← x

3: btProd(node L x R) ← btProd(L) + x + btProd(R )

That's the way i would do it but i'm not sure if that's correct

la3anato
  • 1
  • 3
  • 1
    What have you done thus far? – Mike Tung May 07 '17 at 13:54
  • 1
    Because the multiplication is commutative you can traverse the tree any way you want and multiply all the nodes. – maraca May 07 '17 at 14:05
  • Please try out some steps and post what you tried – Mathews Sunny May 07 '17 at 14:11
  • Add clarification directly to the question itself using [edit]. Comments ([and answers](http://stackoverflow.com/a/43820666/1377097)) are the wrong place to make updates. – beaker May 07 '17 at 14:38
  • Thanks for feedback @beaker – la3anato May 07 '17 at 14:44
  • Your algorithm seems to be fine except that it's not plus, you want the product, so you need to multiply in step 3. – maraca May 07 '17 at 16:23
  • Actually there is another problem, if a node has only one child the algo will return 0, so btProd(null) should return 1 (the neutral element of the multiplication) unless it is the root (then 0). – maraca May 07 '17 at 16:30
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [on topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. StackOverflow is not a design, coding, research, or tutorial service. – Prune May 08 '17 at 16:46

1 Answers1

0

As mentioned in the comments, the product is commutative. Thus, you can traverse the tree in any order you like (pre-,in-,post-order). The recursion you motivated as pseudo-code seems correct, assuming that when you write + x + you mean btProd(L) times btProd(R).

gue
  • 1,868
  • 1
  • 16
  • 21