Binary tree and for a worthwhile path Java implementation

Source: Internet
Author: User

From the point of the sword

The path is a path from the root node to the leaf node, and the sum of the values of each node passing through the path equals a given number, the node on the print path

  • Because you need to print the path node information that satisfies the condition and the sum of each node, you need the node where the stack record passes, and a variable that holds the sum of the values.
  • Using the pre-order traversal method, you can first access the node, then put the node into the stack, and add the value to the node values of the previous stack
  • Determines whether the current node is a leaf node if the current and no satisfies the given value, and the path information is printed
  • Determine whether the child is empty or not, recursive call
  • At the end of the call, return the value of the stack to the stack (the node in the stack is only to the parent node), and the variable will be changed back to the state before the call
  •   

    1     //two fork Tree definition2     classBtree {3         intvalue;4 Btree Leftbtree;5 Btree Rightbtree;6     }7     Privatestack<integer> stack =NewStack<integer>(); 8      Public voidFindpath (Btree node,intSumintcurrsum) {9         Booleanisleaf;Ten         if(node = =NULL) One             return; ACurrsum + =Node.value; - Stack.push (node.value); -IsLeaf = Node.leftbtree = =NULL&& Node.rightbtree = =NULL; the         if(currsum = = Sum &&isleaf) { -System.out.println ("Path:"); -              for(intval:stack) { - System.out.println (val); +             } -         } +         if(Node.leftbtree! =NULL) A Findpath (Node.leftbtree, Sum, currsum); at         if(Node.rightbtree! =NULL) - Findpath (Node.rightbtree, Sum, currsum); -Currsum-=Node.value; - Stack.pop (); -}

Binary tree and for a worthwhile path Java implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.