Try   HackMD

No. 129 - Sum Root to Leaf Numbers

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


LeetCode 129 Sum Root to Leaf Numbers

題目描述

You are given the root of a binary tree containing digits from 0 to 9 only.

Each root-to-leaf path in the tree represents a number.

  • For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.

A leaf node is a node with no children.

Example 1.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

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

解法

本題的目的是把 tree 從 root 到 leaf 看成一個數字然後把每個 root 到 leaf 形成的數字加總起來。

下面為完整的程式碼:

/** * 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 dfs(TreeNode* node, int num) { if (!node) return 0; num = 10 * num + node->val; if (!node->left && !node->right) { return num; } return dfs(node->left, num) + dfs(node->right, num); } int sumNumbers(TreeNode* root) { return dfs(root, 0); } };

我們可以用 DFS 的方法來解,從 root 一路到 leaf,我們要做的就是把當前走訪的 node 加上前面一路累加起來的結果,也就是說假設到當前 node 為止前面累加起來的數字是 num 則 DFS 走訪的當前的 node 會把 num 累加為 num = num * 10 + node->val,然後再看看有沒有下一個 node 或者當前的 node 就是 leaf,若為 leaf 則回傳當前的 num 否則繼續做 DFS。

而最後 DFS 要回傳的是把當前 node 往左右 DFS 回傳的結果相加起來,如此我們就可以把所有 root 到 leaf 的數字加總。

另外我們也要防止當一開始做 DFS 的時候就已經沒有 node,若是這種情況則我們就直接回傳 0。

複雜度分析

時間複雜度上,我們要走訪所有的 node 所以複雜度為

O(N)

空間複雜度上,我們需要存 dfs 的函式 stack,複雜度為

O(N)