Friday, 15 July 2011

java - how to search sum of numbers in Binary Tree? -


I need to find any combination of numbers in the binaries, which will give me the amount I'm looking for . For example, for that number of trees: 9,1,6,3,2,5 If the system gets the sum of 18, then this string will return "9,1,3,5". How can I do this? .

The combination needs to start with root and pathway & amp; The method requires working in backtracking recursion

I have written the code:

  public string path (int sum) {return path (amount, route); } Private string path (integer amount, node t) {if (t == blank) return ""; Sum = sum - t.getNumber (); If (zodiac == 0) returns T.getNumber () + ","; Return path (zodiac, T. leftfone ()) + path (zodiac, T. gatititon ()); }   

Your recursive implementation is actually It is near, but there are some things that require some adjustments.
First, two things need to be done for the recurring implementation:

  1. base case This problem ultimately leads from the point of view of division and win
  2. General case which is used to split the problem into small pieces until reaching the desired base case .
    You have gone into the problem that you are printing only the last node that your yoga is zero The reason is that the reason you revise is because the last call will again return to the method it is called, where the amount is more than zero .


    If that tree reaches one leaf and no amount is found, then it is not present in the sub-tree.
    return "";

    And if amount is is found in sub-tree
    return t.getNumber () + ",";

    Other We have not reached this amount, there are more children nodes
    path (t.getleftSon ()); Path (t.getRightSon ()); Return t.getNumber () + ","


    I have not tested this exact code in an IDE, but the argument must be correct


No comments:

Post a Comment