LeetCode125 Sum Root to Leaf Numbers

Source: Internet
Author: User

Sum Root to Leaf Numbers

Given a binary tree containing digits from only 0-9 , each root-to-leaf path could represent a number.

An example is the Root-to-leaf path 1->2->3 which represents the number 123 .

thinking: Two cross-tree traversal, judging if it is a leaf node, the path of the node to convert to an integer. I've used two stacks in this one.

Stack is used to return to the previous node

Stack1 is used to record every node in the root node to the leaf, stack1 nodes and stack nodes, but the timing of the popup is different. Should pay attention to analysis.

<span style= "color: #333333;"        > public int sumnumbers (TreeNode root) {if (root==null) return 0;        Stack<treenode> stack=new stack<treenode> ();        Stack<treenode> stack1=new stack<treenode> ();        StringBuilder builder=new StringBuilder ();        int sum=0;        TreeNode Current=root; while (current!=null| |!                Stack.isempty ()) {if (current!=null) {Stack.push (current);                Stack1.push (current);            Current=current.left;                }else{Current=stack.pop ();                    if (Current.right==null&¤t.left==null) {for (int i=0;i<stack1.size (); i++)                    {Builder.append (Stack1.get (i). val);                    } sum+=integer.parseint (Builder.tostring ());                    Builder.delete (0, Builder.length ()); </span><span style= "color: #ff0000;">stack1.pop ();//The leaf node calculates the popup </span><span style= "color: #333333;" >}else{</span><span style= "color: #ff0000;" >while (!stack1.isempty ()) {if (Stack1.peek () ==current) break;//when current is present on the right node Stac                  The current node in K has popped stack1.pop (); But the current node in Stack1 does not eject, we want to keep the full node on the path}</span><span style= "color: #333333;"            >} current=current.right;    }} return sum; }</span>


LeetCode125 Sum Root to Leaf Numbers

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.