Final challenge: height, mirror, path sum
After this: Work out a height, mirror a tree and finish a path sum.
This challenge has three steps, and each step is scored on its own. First, work out the height of a tree from the code that builds it. Next, mirror the example tree, which swaps left and right at every node, and read off its level order. Last, finish the recursive line of a function that looks for a path with a given sum.
You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 3Height
Height
The code below builds a different tree. height is the function from the size and height lesson. What does it print?
root = Node(5)root.left = Node(3)root.right = Node(8)root.left.left = Node(1)root.left.left.right = Node(2)root.right.right = Node(9)print(height(root))Node root = new Node(5);root.left = new Node(3);root.right = new Node(8);root.left.left = new Node(1);root.left.left.right = new Node(2);root.right.right = new Node(9);System.out.println(height(root));Mirror
The mirror function below swaps the left and right children at every node. After mirror(root) on the example tree, what does level order return?
def mirror(node): if node is None: return node.left, node.right = node.right, node.left # swap, then mirror both subtrees mirror(node.left) mirror(node.right)static void mirror(Node node) { if (node == null) return; Node tmp = node.left; // swap, then mirror both subtrees node.left = node.right; node.right = tmp; mirror(node.left); mirror(node.right);}Path sum
has_path_sumhasPathSum answers one question: does any path from the root down to a leaf add up to target? The base cases are already written. Finish the recursive line so that it asks both subtrees whether they can make the remaining amount.
def has_path_sum(node, target): if node is None: return False if node.left is None and node.right is None: # a leaf: the path ends here return node.value == target remaining = target - node.value ______________________________ # ← ask both subtrees about the remaining amountstatic boolean hasPathSum(Node node, int target) { if (node == null) return false; if (node.left == null && node.right == null) return node.value == target; // a leaf: the path ends here int remaining = target - node.value; ______________________________ // ← ask both subtrees about the remaining amount}- Work out the height of a tree from the code that builds it, mirror a tree and read off its level order, and finish a path-sum search.