27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Solutions</strong> to Chapter 4 | Trees <strong>and</strong> Graphs<br />

4.1 Implement a function to check if a tree is balanced. For <strong>the</strong> purposes of this question,<br />

a balanced tree is defined to be a tree such that no two leaf nodes differ in distance<br />

from <strong>the</strong> root by more than one.<br />

SOLUTION<br />

pg 54<br />

The idea is very simple: <strong>the</strong> difference of min depth <strong>and</strong> max depth should not exceed 1,<br />

since <strong>the</strong> difference of <strong>the</strong> min <strong>and</strong> <strong>the</strong> max depth is <strong>the</strong> maximum distance difference possible<br />

in <strong>the</strong> tree.<br />

1 public static int maxDepth(TreeNode root) {<br />

2 if (root == null) {<br />

3 return 0;<br />

4 }<br />

5 return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));<br />

6 }<br />

7<br />

8 public static int minDepth(TreeNode root) {<br />

9 if (root == null) {<br />

10 return 0;<br />

11 }<br />

12 return 1 + Math.min(minDepth(root.left), minDepth(root.right));<br />

13 }<br />

14<br />

15 public static boolean isBalanced(TreeNode root){<br />

16 return (maxDepth(root) - minDepth(root)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!