剑指offer 二叉树中和为某一值的路径

二叉树中和为某一值的路径

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

我的解答

思路

这道题我是参考这篇博客的(点击跳转原博客)思路就是设置一个二位vector,也就是这里我们设置的res,然后另外写一个函数专门递归处理题目要求,递归样式也基本是固定的,需要将当前的current和sum都放在函数参数列表中,同时我们还需要传入path,这里path需要的是引用,如果不是引用,当函数递归或者函数执行完成,对于原来path的修改就没有效果了,所以我们需要加上&(引用)。递归的过程读者可以自己模拟一下就清晰了。

代码

//
//  main.cpp
//  offer24
//
//  Created by 李林 on 16/7/24.
//  Copyright © 2016年 李林. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;


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

class Solution {
public:
    TreeNode* Insert(TreeNode* root, int value){
        if(root == NULL)
            root = new TreeNode(value);
        else{
            if(root->val > value)
                root->left = Insert(root->left, value);
            else
                root->right = Insert(root->right, value);
        }
        return root;
    }

    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if(root==NULL){
            return res;
        }

        vector<int> path;
        FindSinglePath(root, path, expectNumber, 0);

        return res;
    }

    //&对地址进行修改,如果不加,函数递归,path失效。
    void FindSinglePath(TreeNode* root,vector<int>& path,  int sum, int current){
        current+=root->val;
        path.push_back(root->val);
        if(root->left==NULL && root->right==NULL){
            if(current == sum)
                res.push_back(path);
        }

        if(root->left)
            FindSinglePath(root->left, path, sum, current);
        if(root->right)
            FindSinglePath(root->right, path, sum, current);

        path.pop_back();
    }

    void InOrder(TreeNode *root){
        InOrder(root->left);
        printf("%d ", root->val);
        InOrder(root->right);
    }

private:
    vector<vector<int>> res;
};

int main() {
    Solution s;
    TreeNode* root = NULL;
    int array[] = {3,2,1,3};

    for(int i=0; i<4; i++)
        root = s.Insert(root, array[i]);
    vector<vector<int>> v = s.FindPath(root, 6);

    for(int i=0; i<2; i++){
        int size = v[i].size();
        for(int j=0; j<size; j++){
            printf("%d ", v[i][j]);
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值