Leetcode129 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.
Note: A leaf is a node with no children.

Example1:
Input: [1,2,3]
    1
   / \
  2   3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Input: [4,9,0,5,1]
    4
   / \
  9   0
 / \
5   1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.

思路

这是一个深度遍历问题,初看题目注意力容易被“一条完整路径构成一个整数”这样的概念所限制,好像只有知道完整路径才能做计算一样。
实际上如果执着于获取深度,以叶子节点为个位,从下往上相加,就会把问题变得复杂。如果逆向思维,无需知道深度,只要将上一层的数乘10就是进了一位,到叶子节点时返回结果就可以了。

复杂度分析

每个节点遍历一次,复杂度为 O ( n )

方法1:直观的记录路径

class Solution {
public:
    int sum=0;
    int num[100];
    void AddSum(int n)
    {
        for(int i=0;i<=n;i++)
        {
            sum+=pow(10,n-i)*num[i];
        }
    }
    void dfs(TreeNode*root,int level)
    {
        if(root==NULL)
        {
            return; 
        }

        num[level]=root->val;

        if(root->left==NULL&&root->right==NULL)
        {
            AddSum(level);
            return;
        }
        dfs(root->left,level+1);
        dfs(root->right,level+1);
    }

    int sumNumbers(TreeNode* root) {      
        dfs(root,0);
        return sum;
    }
};

方法2:更简洁的做法

class Solution {
public:
    int dfs(TreeNode*root,int sum)
    {
        if(root==NULL)return 0;

        sum=sum*10+root->val;
        if(root->left==NULL&&root->right==NULL)
            return sum;

        return dfs(root->left,sum)+dfs(root->right,sum);
    }

    int sumNumbers(TreeNode* root) {      
        return dfs(root,0);
    }
};

飞翔的魔女
果然景色还是要在路上看比较精彩。

猜你喜欢

转载自blog.csdn.net/qq_24634505/article/details/80675164