leetcode:Sum Root to Leaf Numbers

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,

    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.

題目意思:按要求計算二叉樹每一條分支的和;最後返回所有分支的和。

解題思路:

1,樹中有3類結點:孩子結點,中間節點,空結點

2,對於不同的結點類型返回不同的值;

如果是空節點,返回0;如果是中間節點,返回左右子樹的計算和;如果是孩子節點,返回當前計算和*10加上孩子節點的值;

由此遞歸計算出所有分支的和。

AC代碼:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode *root) {
        if(root == NULL) return 0;
        else if(root->left == NULL && root->right == NULL) return root->val;
        
        int sum = 0;
        
        sum = add(root,0);
        
        return sum;
    }
private:
    int add(TreeNode *node,int curSum){
        //如果是空結點,返回0
        if(node == NULL) return 0;
        //如果是葉子結點,返回當前值的和加上葉子結點的值
        else if(node->left == NULL && node->right == NULL){
            return curSum * 10 + node->val;
        }
        //如果是中間節點,返回左右節點的和
        else{
            return add(node->left,curSum * 10 + node->val) + add(node->right,curSum * 10 + node->val);
        }
    }
};




發佈了47 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章