算法作業HW11:Leetcode90 Path Sum

Description:

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.

Note:

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.

Solution:

  Analysis and Thinking:

本體要求依據數的二叉樹以及給定的和值sum,判斷二叉樹中是否存在路徑,使得路徑上所有節點相加的值等於sum值,有則返回True,否則返回False。這一題最簡單的解法之一就是利用遞歸法的思想,結合深度遍歷樹的做法。重點在於:一是特殊情況處理如輸入的是空樹則對於任sum值都爲false。二是對於遞歸的當前節點爲空,說明路徑不同,返回false。三是若當前節點爲葉節點,且值等於輸入的sum值,返回true。最後是如果非葉節點,深度遍歷左右子樹。

 

  Steps:

1.判斷當前節點是否爲空,如果是,返回false

2.判斷當前節點是否爲葉節點,如果是,且其值等於參數sum值,返回true

3.將sum減去當前節點值,模擬出一個按路徑相加的效果,深度遍歷當前節點的左右子樹



Codes:

class Solution
{
public:
    bool hasPathSum(TreeNode *root,int sum)
    {
        if(root==NULL) return false;  //判斷當前節點是否爲空,若是,返回false,不通
        
        if(!root->left&&!root->right&&root->pointValue==sum) return true;  //當前爲葉節點,且節點值等於參數sum,說明該路徑滿足條件
        
        int record=sum-root->pointValue;  //減去當前節點值,相當於記錄了路徑的相加和的效果
        return hasPathSum(root->left,record)||hasPathSum(root->right,recorc); //搜索當前節點左右子樹
    }
};



Results:


發佈了35 篇原創文章 · 獲贊 0 · 訪問量 4636
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章