0

So I'm currently practicing DFS & BFS approaches to binary trees and I am confused on how multiple arguments are being passed into the .append statements below. I know that .append can only take one argument and that when the the arguments are encapsulated in parenthesis they are treated as so, but what does it mean when you encapsulate them?

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """ 
        stack = []
        if root is not None:
            stack.append((1, root)) # <---- Here

        depth = 0
        while stack != []:
            current_depth, root = stack.pop()
            if root is not None:
                depth = max(depth, current_depth)
                stack.append((current_depth + 1, root.left))  # <---- Here
                stack.append((current_depth + 1, root.right))  # <---- Here

        return depth

To reiterate, what does .append((arg1, arg2)) mean? How are those args treated and what logic is behind it?

William Merritt
  • 429
  • 1
  • 5
  • 12
  • `(1, root)` creates a tuple here... That's about it really... see: https://docs.python.org/3/library/stdtypes.html#tuple – Jon Clements Dec 15 '18 at 17:29
  • You are passing a tuple as argument to `.append()`. – Austin Dec 15 '18 at 17:29
  • The key insight is the tuple mimics arguments to functions on the call stack. The list is being treated as a FIFO, just like the call stack you'd use if you wrote this recursively. You can think of each element in the list as a stack frame, or "state"/"node" in the search space. – ggorlen Dec 15 '18 at 17:31
  • As to what the logic is behind it.... it appears they're getting unpacked by doing `current_depth, root = stack.pop())`... for use... – Jon Clements Dec 15 '18 at 17:31
  • @timgeb That seems like a poor dupe target... In this question the tuple is not used to extend the list, quite the opposite, it's used as a single argument. – Norrius Dec 15 '18 at 17:43
  • @Norrius well the dupe exactly explains what appending of an iterable does in the accepted answer. – timgeb Dec 15 '18 at 17:48

0 Answers0