"112-path Sum (Path and)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such this adding up all the values along the Path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5 4 8 / 11 13 4 / \ 7 2 1
Return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Main Topic
Given a binary tree and a sum, judging from the root node of the tree to all nodes of the leaf node and whether the sum equals the given and, if equal, returns True, otherwise returns false.
Thinking of solving problems
The tree is traversed, and the backtracking method is used to solve it.
Code Implementation
Tree Node class
publicclass TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
Algorithm implementation class
Public class solution { Private BooleanStop =false;//Determine if the answer has been found Public Boolean Haspathsum(TreeNode root,intSUM) {Calculate (root,0, sum);returnStop }/** * Calculates the root-to-leaf node and the nodes that are currently being processed by @param node * @param cur all nodes from the root node to the current node and * @param. /c10> sum required and */ Private void Calculate(TreeNode node,intCurintSUM) {if(!stop && Node! =NULL) {//The answer is not found, and the node to be processed is not empty //If it is a leaf node, it checks the sum from the root to the current leaf node, and if it is a description already found, change the stop if(Node.left = =NULL&& Node.right = =NULL&& (node.val + cur = = sum)) {stop =true; }//If non-leaf node, continue processing if(Node.left! =NULL) {Calculate (node.left, cur + node.val, sum); }if(Node.right! =NULL) {Calculate (node.right, cur + node.val, sum); } } }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47414069"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "112-path Sum (Path and)"