"113-path Sum II (Path and II)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
Given a binary tree and a sum, find all root-to-leaf paths where each path ' s sum equals the Given sum.
For example:
Given the below binary tree and sum = 22,
5 4 8 / 11 13 4 / \ 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
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 equal to the given sum, if equal to record this path.
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
ImportJava.Util.ArrayList;ImportJava.Util.LinkedList;ImportJava.Util.List; PublicClass Solution {Private List<List<Integer>>ResultPrivate List<Integer>LPrivateIntsum;Privateint Cursum= 0; Public List<List<Integer>>Pathsum (TreeNode root, intsum) {Result= NewLinkedList<>();if(Root!= NULL) {This.sum = sum; L= NewLinkedList<>(); Pathsum (root); }returnResult }Private voidPathsum (TreeNode root) {if(Root!= NULL) {L.Add (Root.Val); Cursum+=Root.Valif(Root.Left== NULL &&Root.Right== NULL &&Cursum== sum) {List<Integer> List = NewLinkedList<>(); for (IntegerI:L) {List.Add (i); } result.AddList); }if(Root.Left!= NULL) {Pathsum (root.left); }if(Root.Right!= NULL) {Pathsum (root.right); } cursum-=Root.Val L.Remove (l.Size ()- 1);//Delete last} }}
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/47438073"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "113-path Sum II (path and)"