public class Solution {
public int sumNumbers(TreeNode root) {
if(root==null){
return 0;
}
int sum = 0;
TreeNode curr;
Stack<TreeNode> ws = new Stack<TreeNode>();
ws.push(root);
while(!ws.empty()){
curr = ws.pop();
if(curr.right!=null){
curr.right.val = curr.val*10+curr.right.val;
ws.push(curr.right);
}
if(curr.left!=null){
curr.left.val = curr.val*10+curr.left.val;
ws.push(curr.left);
}
if(curr.left==null && curr.right==null){ // leaf node
sum+=curr.val;
}
}
return sum;
}
}
Nonrecursive preorder traverse Java solution


@demonxiaojian said in Nonrecursive preorder traverse Java solution:
I think it is not preorder, it's level order using BFS.
and your code modified value of each node, which is not ideal, you may use a list to store it.

@lxclinton I like the way you solved using Preorder traversal iteratively. It's different from others, that said, changing a value of each node may not be ideal sometimes. Nevertheless, it looks different !!!

It is actually preorder.
Since it is using a stack, it puts three if statement: right node, left node, leaf node into the stack.But when we pop out of stack(LIFO) we reverse that order, we actually start from root, then left, then right, so it is definitely preorder. Smart solution!