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