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

    题目描述:

    输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

    解题思路:

    树的题直接想到用递归求解,由于需要数组长度大的考前,用dfs。同时注意,对于不满足的情况,需要回溯。

    代码:

    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };*/
    class Solution {
    public:
        void FindPathCore(vector<vector<int>> &res, TreeNode* cur, vector<int>& tmp, int expectNumber, int& sum)
        {
            if(cur==nullptr)
                return;
            if(cur->left==nullptr && cur->right==nullptr && sum+cur->val==expectNumber)
            {
                tmp.push_back(cur->val);
                res.push_back(tmp);
                tmp.pop_back();
                return;
            }
            sum = sum+cur->val;
            tmp.push_back(cur->val);
            FindPathCore(res, cur->left, tmp, expectNumber, sum);
            FindPathCore(res, cur->right, tmp, expectNumber, sum);
            tmp.pop_back();
            sum = sum-cur->val;
        }
        vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            vector<vector<int>>res;
            if(root==nullptr)
                return res;
            int sum = 0;
            vector<int> tmp;
            FindPathCore(res, root, tmp, expectNumber, sum);
            return res;
        }
    };
  • 相关阅读:
    node.js----服务器http
    node.js---对文件操作
    node.js
    历史管理
    h5
    git与github
    js中面向对象(创建对象的几种方式)
    jq基础
    POJ 2492 A Bug's Life
    POJ 1742 Coins
  • 原文地址:https://www.cnblogs.com/LJ-LJ/p/11305691.html
Copyright © 2011-2022 走看看