每日三題(4)

Leetcode112.路徑總和

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        return is_sum(root,sum);
    }
    bool is_sum(TreeNode * root,int sum){
        if(root == NULL){
            return false;
        }
        if(!root->right && !root->left){
            if(sum == root->val){
                return true;
            }
        }
        return (is_sum(root->left,sum-root->val) || is_sum(root->right,sum-root->val));
    }
};

思路:遞歸判斷root的子樹和是否等於sum-root->val
Leetcode113.路徑總和II

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> vec;
        vector<int> v;
        is_sum(vec,v,root,sum);
        return vec;
    }
    void is_sum(vector<vector<int>> &vec,vector<int> v,  TreeNode *root,int sum){  //注意此處的v沒有引用
        if(root == nullptr) return;
        v.push_back(root->val);
        if(root->val == sum && root->left == nullptr && root->right == nullptr ){
            vec.push_back(v);
        } 
        is_sum(vec,v,root->left,sum-root->val);
           is_sum(vec,v,root->right,sum-root->val);

    }
};

**思路:**因爲要存儲相加等於sum的節點的值所以使用vector<vector>類型容器存儲,當存在和爲sum的節點時,先存到vector v中,再講vector v存到vector<vector>。注意:,vector v 並不使用引用,有回溯過程。
Leetcode 94.二叉樹的中序遍歷

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> vec;
    vector<int> inorderTraversal(TreeNode* root) {
           inorder_binary(root);
            return vec;

    }
    void inorder_binary(TreeNode * root){
          if(root == nullptr) return ;
        inorderTraversal(root->left);
        vec.push_back(root->val);
        inorderTraversal(root->right);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章