Ruby solution O(n)


  • 0

    Run DFS, returning the node's level-index (and adding its value at that level).

    Using Ruby mainly because of the out[i] ||= [].

    def find_leaves(root)
      out = []
      dfs = -> node {
        return -1 if !node
        i = 1 + [dfs[node.left], dfs[node.right]].max
        (out[i] ||= []) << node.val
        i
      }
      dfs[root]
      out
    end

Log in to reply
 

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