[LeetCode] 1022. Sum of Root To Leaf Binary Numbers 從根到葉的二進位數之和

2021-03-02 刷盡天下

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 answer is guaranteed to fit in a 32-bits integer.

Example 1:

Input: root = [1,0,1,0,1,0,1]

Output: 22

Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Example 2:

Input: root = [0]

Output: 0

Example 3:

Input: root = [1]

Output: 1

Example 4:

Input: root = [1,1]

Output: 3

Constraints:

這道題給了一個結點值為0或1的二叉樹,讓返回所有從根結點到葉結點的路徑組成的二進位數字的和。實際上就是一道變形的路徑之和的題目,關於路徑之和,LeetCode 有很多道題目,比如 Path Sum IV,Path Sum III,Binary Tree Maximum Path Sum,Path Sum II,Path Sum,和 Minimum Path Sum 等等。還是要用遞歸來做,就使用先序遍歷就可以了,使用一個變量 cur 記錄從根結點到當前結點的路徑的二進位數對應的十進位的值,每當新加一個結點時,當前的數字要左移一位,也就是乘以2,再加上當前的結點值。若當前結點是個葉結點,則說明一條完整的路徑已經找到了,將數字加入結果 res,然後對左右子結點分別調用遞歸函數即可,參見代碼如下:

解法一:

class Solution {public:    int sumRootToLeaf(TreeNode* root) {        int res = 0;        helper(root, 0, res);        return res;    }    void helper(TreeNode* node, int cur, int& res) {        if (!node) return;        cur = cur * 2 + node->val;        if (!node->left && !node->right) {            res += cur;        }        helper(node->left, cur, res);        helper(node->right, cur, res);    }};

我們也可以寫的更簡潔一些,讓 helper 函數返迴路徑之和的值,這樣在更新完 cur 之和,只要判斷是否是葉結點,是的話直接返回 cur,否則返回對左右子結點調用遞歸函數的返回值之和即可,參見代碼如下:

解法二:

class Solution {public:    int sumRootToLeaf(TreeNode* root) {        return helper(root, 0);    }    int helper(TreeNode* node, int cur) {        if (!node) return 0;        cur = cur * 2 + node->val;        return node->left == node->right ? cur : helper(node->left, cur) + helper(node->right, cur);    }};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1022

類似題目:

Path Sum IV

Path Sum III

Binary Tree Maximum Path Sum

Path Sum II

Path Sum

Minimum Path Sum

參考資料:

https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/

https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/270600/Java-Simple-DFS

https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/270025/JavaC%2B%2BPython-Recursive-Solution

LeetCode All in One 題目講解匯總(持續更新中...)

相關焦點

  • LeetCode-18.四數之和(4Sum)
    滿足要求的四元組集合為:[ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2]]來源:力扣(LeetCode)連結:https://leetcode-cn.com/problems/4sum/Link:https://leetcode.com/problems/4sum/雙指針O(N^
  • LeetCode-1.兩數之和(Two Sum)
    相信每個想刷leetcode的人,第一次打開網站,就從這道題開始的。一起起航吧,Great Voyage.
  • 四數之和(18)-四數之和(454)-LeetCode
    滿足要求的四元組集合為:[[-1,  0, 0, 1], [-2, -1, 1, 2], [-2,  0, 0, 2]]來源:LeetCode連結:https://leetcode-cn.com/problems/4sum(1)排序+雙指針    延續兩數之和、三數之和的雙指針+排序解題思路
  • 兩個二進位數相加
    陸小鳳原創本文講解「兩個二進位數相加」的算法題。
  • 三數之和 | Leetcode題解
    兩數之和。這個問題是比較簡單的, 我們只需要對數組進行排序,然後雙指針解決即可。加上需要外層遍歷依次數組,因此總的時間複雜度應該是 O(N^2)。15.3-sum在這裡之所以要排序解決是因為, 我們算法的瓶頸在這裡不在於排序,而在於 O(N^2),如果我們瓶頸是排序,就可以考慮別的方式了。
  • LeetCode 攻略 - 2019 年 7 月下半月匯總(100 題攻略)
    | 目錄 || --- | | 一 目錄 | | 二 前言 || 三 匯總 ||  3.1 LeetCode 已攻略 ||  3.2 Function & Object || 四 總結 |001 - 兩數之和(two-sum) ✔007 - 整數反轉(reverse-integer) ✔009 - 迴文數(palindrome-number
  • LeetCode-15.三數之和(3Sum)
    三數之和給你一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有滿足條件且不重複的三元組。注意:答案中不可以包含重複的三元組。
  • Python binarytree庫的用法介紹
    __all__ = ['Node', 'tree', 'bst', 'heap', 'build', 'get_parent']二、tree生成一棵普通二叉樹from binarytree import *tree0 = tree()print
  • Python零基礎入門——認識二進位數
    在上一節課,我們安排了一個課後練習,要求同學們繪製求兩數和算法的流程圖。求兩數和算法的步驟如下:(1)獲取用戶輸入的兩個加數,分別存儲到num1和num2兩個變量;(2)求num1和num2兩數的和,將和存儲到sum變量;(3)將sum變量輸出到電腦屏幕。
  • 三數之和姊妹題——LeetCode題目16:最接近的三數之和
    返回這三個數的和。假定每組輸入只存在唯一答案。示例輸入:nums=[-1, 2, 1, 4], target=1輸出:2解釋:與 target 最接近的三個數的和為 2. (-1 + 2 + 1 = 2).
  • leetcode-15三數之和
    三數之和:https://leetcode-cn.com/problems/3sum/1、題目描述
  • 數據結構與算法:16 Leetcode同步練習(六)
    二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。說明: 葉子節點是指沒有子節點的節點。假設我們要求a^b,那麼b可以拆成二進位表示,例如當b = 5時,5的二進位是0101,5 = 2^3×0 + 2^2×1 + 2^1×0 + 2^0×1,因此,我們將a^5轉化為算 a^(2^3×0 + 2^2×1 + 2^1×0 + 2^0×1),即a^(2^0) × a^(2^2)。
  • Lowest Common Ancestor of Deepest Leaves 最深葉結點的最小公共父節點
    Recall that:The node of a binary tree is a leaf if and only if it has no childrenThe depth of the root of the tree is 0, and if the depth of a node is d, the depth of each of its children
  • ​LeetCode刷題實戰124:二叉樹中的最大路徑和
    今天和大家聊的問題叫做 二叉樹中的最大路徑和,我們先來看題面:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/Given a non-empty binary tree, find the maximum path sum.
  • 「leetcode系列」第一期 二進位表示中質數個計算置位
    Prime Number of Set Bits in Binary RepresentationGiven two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary
  • [leetcode] 2. Add Two Numbers
    The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.