Leetcode 1022. Sum of Root To Leaf Binary Numbers

dfs

class Solution:
    def sumRootToLeaf(self, root: TreeNode) -> int:
        stack=[(root,0)]
        ans=[]
        bi_str=[]
        while stack:
            node,level=stack.pop()
            s_len=len(bi_str)
            if s_len-1<level:
                bi_str.append(str(node.val))
            else:
                bi_str[level]=str(node.val)
                del bi_str[level+1:]
            if (not node.left) and (not node.right):
                ans.append(int(''.join(bi_str),2))
            if node.right:
                stack.append((node.right,level+1))
            if node.left:
                stack.append((node.left,level+1))
        return sum(ans)

 

posted @ 2019-04-24 07:27  周洋  阅读(362)  评论(0编辑  收藏  举报