<LeetCode>112. 路径总和&&257. 二叉树的所有路径

112.给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例: 
给定如下二叉树,以及目标和 sum = 22

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

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2


给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

这两题我的解题思路是一样的:

257:这一题是我在网上参考别人的,下一题是用的同样的思路做的。

class Solution {
public:
    /**
     * @param root the root of the binary tree
     * @return all root-to-leaf paths
     */
      
    /*
    分析:一般二叉树的问题用递归解决比较简洁。这里其实是先序遍历;
    在库文件string中,to_string(int value)是把一个整数转换为字符串;
    两个字符串使用“+”连接,是字符串的无空格连接,这点需要了解下面给出代码:
    */
    vector<string> binaryTreePaths(TreeNode* root) {
        // Write your code here
        vector<string> res;
        if(root==NULL) return res;
        binaryTreePathsCore(root,res,to_string(root->val));
        return res;
    }
     
    void binaryTreePathsCore(TreeNode* root,vector<string> &str,string strpath){
         
        if(root->left==NULL&&root->right==NULL){
            //叶子结点
            str.push_back(strpath);
            return;
        }
        if(root->left!=NULL){
            binaryTreePathsCore(root->left,str,strpath+"->"+to_string(root->left->val));
        }
        if(root->right!=NULL){
            binaryTreePathsCore(root->right,str,strpath+"->"+to_string(root->right->val));
        }
    }
};

112:

/**
 * 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) {
        vector<int> res;
        //if(root==NULL) return false;
        DFS(root,root->val,res);
        auto iter = find(res.begin(),res.end(),sum);
        if(iter != res.end()){
            return true;
        }
        else
            return false;
    }
    void DFS(TreeNode* root, int sum,vector<int>& res)
    {
        if(root->left == NULL && root->right == NULL){
            res.push_back(sum);
            return;
        }
        if(root->left!=NULL)
            DFS(root->left,sum+root->left->val,res);
        if(root->right!=NULL)
            DFS(root->right,sum+root->right->val,res);

    }
};

猜你喜欢

转载自blog.csdn.net/w8253497062015/article/details/80982825