C# iterative stack solution


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

Log in to reply
 

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