Path Sum 2--java two fork depth traversal, save path

Source: Internet
Author: User

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

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.