返回

[Leetcode]129. Sum Root to Leaf Numbers(C++)

题目描述

题目链接:129. 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.

例子

例子 1

Input: [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.

例子 2

Input: [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.

Note

A leaf is a node with no children.

解题思路

采用 dfs 遍历二叉树,传入当前路径的和,执行以下操作:

  • 如果节点为空,直接返回
  • 否则,将当前值先乘 10,再加上当前节点值
  • 如果当前节点是叶节点,则将当前路径和加入结果中
  • 否则对左右子树递归执行操作

代码如下:

class Solution {
public:
    int sumNumbers(TreeNode* root) {
        int result = 0;
        dfs(root, 0, result);
        return result;
    }

private:
    void dfs(TreeNode* root, int current_sum, int& result) {
        if (!root) return;
        current_sum *= 10;
        current_sum += root->val;
        if (!root->left && !root->right) {
            result += current_sum;
        }

        dfs(root->left, current_sum, result);
        dfs(root->right, current_sum, result);
    }
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(h)

GitHub 代码同步地址: 129.SumRootToLeafNumbers.cpp

其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions

Built with Hugo
Theme Stack designed by Jimmy