DFS on a binary tree: marking nodes as visited I wanted to write depth first search reversal iteratively in Java. Can someone review my code? I'm not that much interested in naming of the variables, but in the structure of the code, i.e. I don't need to mark the nodes as visited when I traverse binary tree, right?

public static void dfs(TreeNode root){
        if(root == null)    return;
        Stack&lt;TreeNode&gt; res = new Stack&lt;TreeNode&gt;();
        res.push(root);
        while(!res.isEmpty()){
            TreeNode top = res.pop();
            System.out.print(top.val + " ");
            if(top.right != null)
                res.push(top.right);
            if(top.left!= null)
                res.push(top.left);
        }
    }


Recursive version:

public static void dfs(TreeNode root){
        if(root == null)    return;
        System.out.print(root.val + " ");
        dfs(root.left);
        dfs(root.right);
    }
I don't need to mark the nodes as visited, when I traverse binary tree, right?


Well, is your code working even though you are not doing this right now? Then yes, you don't need it.

See also this question for a theoretical discussion about marking nodes as visited, and this question for a practical reason to mark nodes (it's not needed for a simple search, but it is needed when looking for paths).

Naming

Even though you are not that interested, it is important. It makes your code more readable, which helps reviewers review your code. If you don't really care about your code, why should we?

In this case, it's not really that bad (there aren't all that many variables), but I wouldn't even know what res was short for (rest? Like the rest of the nodes?); even nodes would be better. 

Formatting

Just like naming, correct formatting makes code easier to read and thus easier to maintain and review. Again, your code is very short, so it's not all that bad, but your spacing is off and you should use curly braces even for one-line statements.

Printing

Your code isn't really testable or practical as it doesn't return a result, but just prints something. You should return true (or the node) or false instead if your using it as a search, and return a string/list/etc if your using it to traverse the tree and collect the content of the nodes.