Embercode
✕
Binary TreesQuick quiz

Mirror, symmetry and subtrees

8 questions. Covers Same tree and subtree checks in Python.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``python class TreeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def invert(node): if node is None: return None old_left = node.left node.left = invert(node.right) node.right = invert(old_left) return node def show(node): if node is None: return "None" return "(" + str(node.value) + " " + show(node.left) + " " + show(node.right) + ")" root = TreeNode(5, TreeNode(3, None, TreeNode(4)), TreeNode(8, TreeNode(6), None)) invert(root) print(show(root)) ``
  2. 2. What does this program print? ``python class TreeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def is_mirror(a, b): if a is None and b is None: return True if a is None or b is None: return False return a.value == b.value and is_mirror(a.left, b.right) and is_mirror(a.right, b.left) def is_symmetric(root): return root is None or is_mirror(root.left, root.right) sym = TreeNode(7, TreeNode(4, TreeNode(1), TreeNode(2)), TreeNode(4, TreeNode(2), TreeNode(1))) lopsided = TreeNode(7, TreeNode(4, TreeNode(1)), TreeNode(4, TreeNode(1))) print(is_symmetric(sym), is_symmetric(lopsided), is_mirror(sym.left, sym.right)) ``
  3. 3. This is_mirror is meant to say whether a and b are mirror images. What is wrong with its two recursive calls? ``python def is_mirror(a, b): if a is None and b is None: return True if a is None or b is None: return False return a.val == b.val and is_mirror(a.left, b.left) and is_mirror(a.right, b.right) ``
  4. 4. This looks_symmetric is meant to say whether a tree is symmetric. Which input gives a wrong answer? ``python def looks_symmetric(root): return root is None or root.left.val == root.right.val ``
  5. 5. Why does the queue version of the symmetry check use deque and popleft() instead of a list with pop(0)?

5 question(s) left on this page.