跳至主要内容

129. Sum Root to Leaf Numbers

Hint

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr, right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
// Main function to initiate the DFS and return the total sum of all root-to-leaf numbers
int sumNumbers(TreeNode* root) {

}

// Helper function to perform DFS traversal
int dfs(TreeNode* root, int sum) {
// If the current node is null, return 0 (base case for null nodes)

// Update the sum by incorporating the current node's value


// If the current node is a leaf (no children), return the computed sum

// Recursively calculate the sum for left and right subtrees and return their sum
}
};

  • DFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root)
{
return dfs(root, 0);
}
int dfs(TreeNode* root, int sum)
{
if (!root) return 0;
sum = sum * 10 + root->val;
if (!root->left && !root->right) return sum;
return dfs(root->left, sum) + dfs(root->right, sum);
}
};
  • T: O(n)O(n)
  • S: O(H)O(H)