C# - iterative with Stack


  • 1
    public IList<int> PreorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        List<int> list = new List<int>();
        stack.Push(root);
        while (stack.Count() > 0)
        {
            TreeNode current = stack.Pop();
            if (current != null)
            {
                list.Add(current.val);
                stack.Push(current.right);
                stack.Push(current.left);
            }
        }
        
        return list;
    }

Log in to reply
 

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