Simple stack solution in C#


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

Log in to reply
 

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