Not so great with space, but non-recursive and extreeeeemely simple


  • 0
    V
    public int SumNumbers(TreeNode root) {
            
            if(root == null) return 0;
            
            int currentNumber = 0;
            int total = 0;
            var t = root;
            var stack = new Stack<TreeNode>();
            var hashTable = new Dictionary<TreeNode, int>();
            
            while(t != null || stack.Count > 0)
            {
                if(t != null)
                {
                    stack.Push(t);
                    currentNumber = currentNumber * 10 + t.val;
                    hashTable.Add(t, currentNumber);
                    t = t.left;
                }
                else
                {
                    t = stack.Pop();
                    if(t.left == null && t.right == null)
                    {
                        total = total + hashTable[t];
                    }
                    currentNumber = hashTable[t];
                    t = t.right;
                }
            }
            return total;
        }
    

Log in to reply
 

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