https://leetcode.com/problems/sum-root-to-leaf-numbers/
一個包含0~9的二元樹,找到其根節點到葉數。
利用遞迴尋訪概念,探訪到每一個節點時乘以10加上現在節點數值,直到條件不符合時。
int sumNumbers(struct TreeNode* root) {
return helper(root, 0);
}
int helper(struct TreeNode* root, int sum)
{
if(root == NULL)
return 0;
if(root -> left == NULL && root -> right == NULL)
return sum*10 + root -> val;
return helper(root -> left,sum*10+root -> val) + helper(root -> right,sum*10+root -> val);
}
var sumNumbers = function(root) {
let total = 0, sum = 0;
helper(root, sum);
return total;
function helper(node, sum) {
if (!node)
return;
sum = sum*10 + node.val;
if (!node.left && !node.right) {
total += sum;
}
helper(node.left, sum);
helper(node.right, sum);
}
};
https://github.com/SIAOYUCHEN/leetcode
https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136
Every story needs an ending, but there is no ending which is called life.
每個故事都需要一個結局,但沒有結局的,叫做人生