Sum Root to Leaf Numbers

    xiaoxiao2021-12-14  47

    

    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.

    题目的大意是给定一棵二叉树,从根到每个叶子的路径代表了一个数字,题目求所有这些数字的和。

    这道题目比较简单,很容易就可以想到利用深度优先算法来解决这个问题。利用深度优先搜索时,对于每个叶子节点来说,肯定会先遍历叶子节点的所以根结点以后才会遍历该叶子节点,我们只需要用一个变量记录从根节点到该结点的路径所代表的数字,并把这个数字一直传下去,每到一个新的结点,只要把这个数字乘10再加上该结点的值就可以计算出从根节点到该结点的路径所代表的数字,当到达叶子节点时,就可以得到从根节点到这个叶子节点代表的数字,把这个数字加到全局变量sum中,这样遍历完就可以得到所有这些数字的和。

    利用深度优先搜索算法的效率还是比较高的,因为它只需要将所有节点遍历一遍,不需要重复地遍历非叶子节点,由于这是一棵树,利用的是深度优先搜索算法,所以时间复杂度是O(n)。以下为源代码:

    class Solution { public: int sum=0; int sumNumbers(TreeNode* root) { dfs(root,0); return sum; } void dfs(TreeNode* r,int num) { if(r==NULL) return; num=num*10+r->val; if(r->left==NULL&&r->right==NULL) sum+=num; dfs(r->left,num); dfs(r->right,num); } };

    转载请注明原文地址: https://ju.6miu.com/read-970141.html

    最新回复(0)