My Accepted DFS Solution


  • 0
    K
    public List<Integer> preorderTraversal(TreeNode root)
    {
        LinkedList<Integer> result = new LinkedList<Integer>();
    
        if (root == null)
        {
            return result;
        }
        
        LinkedList<TreeNode> visited = new LinkedList<TreeNode>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        TreeNode tempNode = null;
        
        while (!stack.isEmpty())
        {
            tempNode = stack.peek();
            
            if (!visited.contains(tempNode))
            {
                result.add(tempNode.val);
                visited.add(tempNode);
            }
    
            if (tempNode.left != null && !visited.contains(tempNode.left))
            {
                stack.add(tempNode.left);
            }
            else if (tempNode.right != null && !visited.contains(tempNode.right))
            {
                stack.add(tempNode.right);
            }
            else
            {
                stack.pop();
            }
        }
        
        return result;
    }

Log in to reply
 

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