Easy python solution explained


  • 4
    A

    When each node is visited, mark the value of the node as '#', which is treated as if the node is None in tree iteration. Each iteration gives a one level of leaves.

    class Solution(object):
        def findLeaves(self, root):
            def markLeaves(p, l):
                leaf = True
                if p.left and p.left.val!='#':
                    leaf = False
                    markLeaves(p.left, l)
                if p.right and p.right.val!='#':
                    leaf = False
                    markLeaves(p.right, l)
                if leaf:
                    l.append(p.val)
                    p.val = '#'
                    
            ret = []
            p = root
            while(p and p.val!='#'):
                l = []
                markLeaves(p, l)
                ret.append(l)
                p = root
            return ret

  • 0
    W

    This is an actually clean and well-explained solution...
    Why not popular?


Log in to reply
 

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