全部根到葉子結點組組成的數字相加

原題

  Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
  An example is the root-to-leaf path 1->2->3 which represents the number 123.
  Find the total sum of all root-to-leaf numbers.
  For example,git

1
   / \
  2   3

 

  The root-to-leaf path 1->2 represents the number 12.
  The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.算法

題目大意

  給定一個二叉樹,每一個結點的值是0-9,根到葉子組成一個數字,求全部的根到葉子組成的數字的和。spa

解題思路

  採用回溯法。.net

代碼實現

算法實現類code

public class Solution {

    private int result = 0; // 記錄總的結果
    private int num = 0; // 記根到葉子的數字

    public int sumNumbers(TreeNode root) {
        sum(root);
        return result;
    }

    private void sum(TreeNode root) {
        if (root != null) {
            num = num*10 + root.val;

            // 已經到了根結點了
            if (root.left == null && root.right == null) {
                result += num;
            }
            sum(root.left);
            sum(root.right);
            num /= 10;
        }
    }
}
相關文章
相關標籤/搜索