Last Updated on 2022-01-11 by Clay
題目
You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers. The test cases are generated so that the answer fits in a 32-bits integer.
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]
. Node.val
is0
or1
.
題目給定二元樹的資料結構,每個節點上只會存在著 1 或 0 的數值。我們要做的就是遍歷每條從根到葉子的路徑,並將路徑所代表的二進制數值轉換成十進制,再把所有路徑的值加總。
比方說像 Example 1,我們總共有四條可以走到底的路徑:100、101、110、111,我們就是要將其轉換成十進制的 4 + 5 + 6 + 7,最後得到 22 的數字。
解題思路
既然是每條路線都要走到底,那麼第一感就是使用遞迴來做 DFS 了。只需要記得在每次遞迴函式裡頭,都需要將現有值乘 2(或是你習慣用位元運算將數值往左移動一格),這是因為每次加上新的值時,舊的二進制值都會變長的緣故。
C++ 範例程式碼
/**
* 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* root, int ans) {
// Base case
if (!root) return 0;
// Compute the current value
ans = ans * 2 + root->val;
// The recursive reach the endpoint
if (!root->left && !root->right) return ans;
// Return
return DFS(root->left, ans) + DFS(root->right, ans);
}
int sumRootToLeaf(TreeNode* root) {
return DFS(root, 0);
}
};
Python 範例程式碼
class Solution:
def DFS(self, root, ans):
# Base case
if not root: return 0
# Compute the current value
ans = ans * 2 + root.val
# If reach the recursive endpoint
if not root.left and not root.right: return ans
# Return
return self.DFS(root.left, ans) + self.DFS(root.right, ans)
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
return self.DFS(root, 0)