Iteration via stack solution in C#


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

    Well this works, but obviously not the best solution.


Log in to reply
 

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