Java Clean Code - Iterative & Visited Set


  • 1
    C
    public class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
    		if (root == null) {
    			return new ArrayList<>();
    		}
    		List<Integer> list = new ArrayList<>();
    		Stack<TreeNode> stack = new Stack<>();
    		Set<TreeNode> visiteds = new HashSet<>();
    		stack.push(root);
    
    		while(!stack.isEmpty()) {
    			TreeNode node = stack.pop();
    			if (visiteds.contains(node)) {
    				list.add(node.val);
    			} else {
    				if (node.right != null) {
    					stack.push(node.right);
    				}
    				if (node.left != null) {
    					stack.push(node.left);
    				}
    				stack.push(node);
    				visiteds.add(node);
    			}
    		}
    		return list;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.