跳至主要內容

路径代表的数之和


路径代表的数之和

题目

给定一个二叉树,其中每个节点只能有一个数字(0-9)值,每个根到叶路径将代表一个数字。找出所有路径所代表的所有数字的总和。

解答

class TreeNode {
  int val;
  TreeNode left;
  TreeNode right;

  TreeNode(int x) {
    val = x;
  }
};

class SumOfPathNumbers {
  public static int findSumOfPathNumbers(TreeNode root) {
    return findRootToLeafPathNumbers(root, 0);
  }

  private static int findRootToLeafPathNumbers(TreeNode currentNode, int pathSum) {
    if (currentNode == null)
      return 0;

    // 计算当前节点的路径和calculate the path number of the current node
    pathSum = 10 * pathSum + currentNode.val;

    // 如果当前节点是叶子结点,返回路径和
    if (currentNode.left == null && currentNode.right == null) {
      return pathSum;
    }

    // 遍历左右子树
    return findRootToLeafPathNumbers(currentNode.left, pathSum) +
           findRootToLeafPathNumbers(currentNode.right, pathSum);
  }

  public static void main(String[] args) {
    TreeNode root = new TreeNode(1);
    root.left = new TreeNode(0);
    root.right = new TreeNode(1);
    root.left.left = new TreeNode(1);
    root.right.left = new TreeNode(6);
    root.right.right = new TreeNode(5);
    System.out.println("Total Sum of Path Numbers: " + SumOfPathNumbers.findSumOfPathNumbers(root));
  }
}
上次编辑于:
贡献者: Neil