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