Algorithms and Data Structures/Coding Practices

AlgoExpert Node Depths

brightlightkim 2022. 7. 12. 15:30

import java.util.*;

class Program {

  public static int nodeDepths(BinaryTree root) {
    // Write your code here.
    return findNodeSum(root, 0);
  }

  public static int findNodeSum(BinaryTree root, int depth){
    int sum = 0;
    if (root == null){
      return 0;
    }
    sum += depth;
    sum += findNodeSum(root.left, depth + 1);
    sum += findNodeSum(root.right, depth + 1);
    return sum;
  }

  static class BinaryTree {
    int value;
    BinaryTree left;
    BinaryTree right;

    public BinaryTree(int value) {
      this.value = value;
      left = null;
      right = null;
    }
  }
}