Leetcode Path Sum

twisted-fate發表於2019-05-31

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.

遞迴實現

從樹根開始判斷

  • 如果當前是葉子節點等於剩餘和,那麼程式返回真
  • 如果當前節點為空,則放回false
  • 除了以上情況,返回遞迴呼叫左右子節點的結果或值,並且傳入剩餘和扣除當前節點值後的值
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if(root == NULL) return false;
        if(root->left == NULL && root->right == NULL && sum == root->val) return true;
        else return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right, sum-root->val);
    }
};
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if(root == NULL) return false;
        if(root->left == NULL && root->right == NULL) return sum == root->val;
        sum-=root->val;
        return hasPathSum(root->left,sum) || hasPathSum(root->right, sum);
    }
};
遞迴實現

 非遞迴遍歷(根據層次遍歷實現即可)

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

#include <iostream>
#include <queue>

using namespace std;

struct TreeNode{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x): val(x), left(NULL),right(NULL){}
};

struct TreeNodeSum{
    TreeNode *node;
    int sum;
    TreeNodeSum(TreeNode* node_, int sum_ ):node(node_),sum(sum_){}
};

bool hasPathSum(TreeNode *root, int sum) {
    if(root == NULL) return false;
    queue<TreeNodeSum *> que;
    que.push(new TreeNodeSum(root,root->val));
    int res = 0;
    while(!que.empty()){
        TreeNodeSum *tmp = que.front();que.pop();
        TreeNode *node = tmp->node;
        cout<<node->val<<endl;
        if(!node->left && !node->right && tmp->sum == sum) return true; 
        if(node->left){
            TreeNodeSum *nodeSum = new TreeNodeSum(node->left,node->left->val+tmp->sum);
            que.push(nodeSum);
        }
        if(node->right ){
            TreeNodeSum *nodeSum = new TreeNodeSum(node->right,node->right->val+tmp->sum);
            que.push(nodeSum);
        }
    }
    return false;
}

int main(){
    TreeNode *root = new TreeNode(1);

    TreeNode *root1 = new TreeNode(-2);

    TreeNode *root2 = new TreeNode(-3);

    TreeNode *root3 = new TreeNode(1);

    TreeNode *root4 = new TreeNode(3);
    TreeNode *root5 = new TreeNode(-2);
    TreeNode *root6 = new TreeNode(-1);
    root->left = root1;
    root->right = root2;
    root1->left = root3;
    root1->right = root4;
    root2->left = root5;
    root3->left = root6;
    cout<<hasPathSum(root,-1)<<endl;
}
非遞迴實現

相關文章