來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/binary-tree-paths
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。javascript
給定一個二叉樹,返回全部從根節點到葉子節點的路徑。java
說明: 葉子節點是指沒有子節點的節點。node
示例:數組
輸入:網絡
1
/ \
2 3
\
5this
輸出: ["1->2->5", "1->3"]code
解釋: 全部根節點到葉子節點的路徑爲: 1->2->5, 1->3blog
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {string[]} */ var binaryTreePaths = function(root) { let arr = []; if(root){ rode(root,null); } return arr; function rode(root, link){ let nextlink = link ? link + "->" + root.val:root.val+""; if(root.left == null && root.right == null) arr.push(nextlink); else{ if(root.left) rode(root.left,nextlink); if(root.right) rode(root.right,nextlink); } } };
來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。遞歸
給出一棵二叉樹,其上每一個結點的值都是 0 或 1 。每一條從根到葉的路徑都表明一個從最高有效位開始的二進制數。例如,若是路徑爲 0 -> 1 -> 1 -> 0 -> 1,那麼它表示二進制數 01101,也就是 13 。ip
對樹上的每一片葉子,咱們都要找出從根到該葉子的路徑所表示的數字。
以 10^9 + 7 爲模,返回這些數字之和。
示例:
輸入:[1,0,1,0,1,0,1]
輸出:22
解釋:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
提示:
樹中的結點數介於 1 和 1000 之間。
node.val 爲 0 或 1 。
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number} */ var sumRootToLeaf = function(root) { let sum = 0; if(root){ rode(root,0); } return sum % (Math.pow(10, 9) + 7); function rode(root,link){ let nextlink = link * 2 + root.val; if(root.left == null && root.right == null){ sum += nextlink; }else{ if(root.left) rode(root.left,nextlink); if(root.right) rode(root.right,nextlink); } } };