第三周:( LeetCode 112 113 ) Path SumI II(c++)

    xiaoxiao2021-03-25  130

    最近这一周进入了图的分解相关算法的学习,由于这方面以前做题的经验不多,因此每种算法应该会多做几道题,从最简单的dfs开始,本博文选的两道题:leetcode112、113,正是基于图(二叉树)的深度优先遍历的题。113比112多了一个保存路径的步骤,实际上差别不是特别大!

    Path Sum I 原题: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。用dfs递归遍历,递归终结的条件是:(1)当root为null时,说明找不到路径,返回false;(2)当root不为null,但root左右节点均为null,即root为叶子结点,并且路径上所有节点和为sum时,返回true。 代码如下:

    /** * 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) { if (root == NULL) return false; else if (root->left == NULL && root->right == NULL && root->val == sum) return true; else { return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum - root->val); } } };

    Path Sum II 原题:Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum. For example: Given the below binary tree and sum = 22,

    5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1

    return

    [ [5,4,11,2], [5,8,4,5] ]

    思路:本题和上题的区别就是找到和为sum的路径,并把路径输出。也是一样的思路,采用递归dfs遍历,唯一的区别是在遍历的过程中用vector保存path,当path符合要求时把vector添加到result中去。如果熟悉c++的vector和递归return的值,此题和上题基本类似。 代码如下:

    class Solution { public: vector<vector<int>> dfs(TreeNode* root, int sum, vector<vector<int>> res, vector<int> path) { if((root->left==NULL)&&(root->right==NULL)){ if(sum==root->val){ path.push_back(root->val); res.push_back(path); } }else{ path.push_back(root->val); if(root->left!=NULL){ res=dfs(root->left,sum-root->val,res,path); } if(root->right!=NULL){ res=dfs(root->right,sum-root->val,res,path); } } return res; } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; vector<int> path; if(root==NULL) return res; return dfs(root,sum,res,path); } };

    以上两题用递归写的代码简单且容易理解,但效率不高。一切刚刚开始!

    转载请注明原文地址: https://ju.6miu.com/read-5822.html

    最新回复(0)