leetcode:Sum Root to Leaf Numbers

来源:互联网 发布:淘宝写论文谁家靠谱 编辑:程序博客网 时间:2024/05/16 11:26

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);        }    }};




0 0
原创粉丝点击