zoukankan      html  css  js  c++  java
  • [剑指offer] 二叉树中和为某一值的路径

    题目描述

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


    依然是递归,一个关键点是把结果和当前路径与和存储为类的变量,减少了对结果集合和当前路径繁琐的合并与传递等操作。

    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };*/
    class Solution {
    public:
        vector<vector<int> > re;
        vector<int> currentPath;
        int currentSum = 0;
        vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            if (root == NULL) return re;
            currentPath.push_back(root->val);
            currentSum += root->val;
            if (currentSum == expectNumber && root->left == NULL && root->right == NULL) {
                re.push_back(currentPath);
            } else {
                FindPath(root->left, expectNumber);
                FindPath(root->right, expectNumber);
            }
            currentPath.pop_back();
            currentSum -= root->val;
            return re;
        }
    };
  • 相关阅读:
    人生之清单(list of life)
    grpc编译错误解决
    windows tensorflow 版本与升级
    PermissionError: [Errno 13] in python
    经典分析--HTTP协议
    介绍 JSON
    Json 不同语言的使用
    JSON标准格式
    JSON 数据格式
    SKINTOOL 系统不能正常运行
  • 原文地址:https://www.cnblogs.com/zmj97/p/7909303.html
Copyright © 2011-2022 走看看