Simple Python with Preorder Tree Traversal


  • 0
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def sumNumbers(self, root):
            if root == None:
                return 0
            cur = root
            s = [] # declare a stack
            s.append(cur)
            result = []
            while len(s) > 0:
                cur = s.pop()            
                if cur.right != None:
                    cur.right.val += cur.val * 10
                    s.append(cur.right)                
                if cur.left != None:
                    cur.left.val += cur.val * 10
                    s.append(cur.left)
                if (cur.right == None) & (cur.left == None): # this is leaf
                    result.append(cur.val)
            return sum(result)       
    

Log in to reply
 

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