Guest User

Untitled

a guest
Jun 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.67 KB | None | 0 0
  1. class Solution {
  2. public int minDepth(TreeNode root) {
  3. if (root == null) return 0;
  4. return recur(root, 1);
  5. }
  6.  
  7. private int recur(TreeNode root, int depth) {
  8. if (root == null) return 0;
  9. if (root.left == null && root.right == null) {
  10. return depth;
  11. }
  12. int ldepth = recur(root.left, depth + 1);
  13. int rdepth = recur(root.right, depth + 1);
  14.  
  15. // either left or right subtree was not a leaf node
  16. // ignore non leaf node.
  17. if (ldepth == 0 || rdepth == 0) {
  18. return Math.max(ldepth, rdepth);
  19. }
  20. else {
  21. return Math.min(ldepth, rdepth);
  22. }
  23. }
  24. }
Add Comment
Please, Sign In to add comment