lintcode 二叉树的所有路径

很久之前写过有关二叉树的所有路径,今天刷lintcode发现自己忘记了,还是找个地方自己存一下,以后方便自己学习;

二叉树的所有路径

递归出口:最后遍历的节点是叶子节点;

递归条件:如果子树存在则继续递归;

代码:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */




class Solution {
public:
    /*
     * @param root: the root of the binary tree
     * @return: all root-to-leaf paths
     */
    void allpath(TreeNode *root,vector<string> &res,vector<string> &temp)
    {
        temp.push_back(to_string(root->val));
        if(root->left==nullptr&&root->right==nullptr)
        {
            string s;
            string c="->";
            for(int i=0;i<temp.size()-1;i++)
                s=s+temp[i]+c;
            s+=temp.back();
            res.push_back(s);
        }
        if(root->left)
            allpath(root->left,res,temp);
        if(root->right)
            allpath(root->right,res,temp);
        temp.pop_back();
    }
    vector<string> binaryTreePaths(TreeNode * root) {
        // write your code here
        vector<string> res;
        vector<string> temp;
        if(root==nullptr)
            return res;
        allpath(root,res,temp);
        return res;
    }
};

二叉树的路径和

此题和上一题类似,增加了遍历至叶子时,计算此时路径和,和目标值比较;

递归出口:遍历至叶子节点

代码:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */




class Solution {
public:
    /*
     * @param root: the root of binary tree
     * @param target: An integer
     * @return: all valid paths
     */
    void trace(TreeNode * root, vector<vector<int> > &res, vector<int> &temp, int target)
    {
        if(root==nullptr)
            return;
        temp.push_back(root->val);
        int sum=accumulate(temp.begin(),temp.end(),0);
        if(root->left==nullptr&&root->right==nullptr&&sum==target)
                res.push_back(temp);
        if(root->left)
            trace(root->left,res,temp,target);
        if(root->right)
            trace(root->right,res,temp,target);
        temp.pop_back();
    }
    vector<vector<int>> binaryTreePathSum(TreeNode * root, int target) {
        // write your code here
        vector<vector<int> > res;
        vector<int> temp;
        trace(root,res,temp,target);
        return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值