In Path SUm 1 (http://www.cnblogs.com/hitkb/p/4242822.html)
We save the path in the form of a stack, and each time we find a matching leaf node, the elements in the stack are output. Note the case where multiple paths exist.
PublicList<list<integer>> pathsum (TreeNode root,intsum) {List<list<integer>>list=NewArraylist<>(); Stack<TreeNode> stack =NewStack<>(); intTotal = 0; if(Root = =NULL) returnlist; TreeNode Qnode=Root; while(Root! =NULL) { while(Root.left! =NULL) {Stack.push (root); Total+=Root.val; Root=Root.left; }//left node compression stack while(Root! =NULL&& (Root.right = =NULL|| Root.right = = Qnode)) {//|| The front is to determine if it is a leaf node, followed by a popup right node if(root.right==NULL&&root.left==NULL){ if((total+root.val) ==sum) {//here is the detection of the current access plus the final leaf node, whether equal to the input. List.add (Getstack (stack,root.val)); }} Qnode= root;//record previous output node if(Stack.empty ())returnlist; Root=Stack.pop (); Total-=Root.val; } stack.push (root); Total+=Root.val; Root=Root.right; } returnlist; } /*statistics stack inside elements * **/ PublicList<integer> Getstack (stack<treenode>Stack,integer a) {Stack<treenode>stack2= (stack<treenode>) Stack.clone (); List<integer>list=NewArraylist<>(); List.add (a); while(!Stack2.isempty ()) {TreeNode Outreenode=Stack2.pop (); List.add (0, Outreenode.val); } returnlist; }
Path Sum 2--java two fork depth traversal, save path