官網題目敘述:

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

過關時間:

 
這題算是簡單反正就找遍所有節點如果到末端剛好等於sum就回傳ture,這邊我用遞迴的方式去做,實際跑起來應該類似深度搜尋。
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**

 * @param {TreeNode} root
 * @param {number} sum
 * @return {boolean}
 */

var hasPathSum = function(root, sum) {
    if(root===null)return false;
    sum-=root.val;
    if(sum===0 && (root.left===null && root.right===null))return true;
    return hasPathSum(root.left,sum) || hasPathSum(root.right,sum);
 }

 

arrow
arrow
    文章標籤
    leetcode 學習網 javascript
    全站熱搜
    創作者介紹
    創作者 Deyu 的頭像
    Deyu

    西瓜是肥貓

    Deyu 發表在 痞客邦 留言(0) 人氣()