【剑指Offer-举例让抽象问题具体化】面试题34:二叉树中和为某一值的路径

题目描述

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

思路

使用dfs和回溯。当遍历到某一结点时,记录当前路径的长度:如果当前长度小于期待长度,将当前结点加入路径中继续遍历;如果当前长度大于期待长度,则该路径已不可能;如果当前长度等于期待长度且当前结点是叶子结点,则找到一条路径。代码如下:

/*
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> > FindPath(TreeNode* root,int expectNumber) {
        vector<int> path;
        vector<vector<int>> ans;
        int curLen = 0;    //当前路径长度
        FindPathCore(root, expectNumber, curLen, path, ans);
        
        return ans;
    }
    
    void FindPathCore(TreeNode* root, int expectNum, int curLen, vector<int> path, vector<vector<int>>& ans){
        if(root==nullptr)
            return;
        curLen+=root->val;
        if(curLen>expectNum)    //当前值大于期待值,该路径已不可能
            return;
        if(curLen<expectNum)    //当前值小于期待值,将当前结点加入路径
            path.push_back(root->val);
        if(curLen==expectNum){    //当前值等于期待值
            if(root->left==nullptr && root->right==nullptr){  //当为叶子节点时才是正确的路径
                path.push_back(root->val);
                ans.push_back(path);
            }
            else path.push_back(root->val);
        }
        
        FindPathCore(root->left, expectNum, curLen, path, ans);
        FindPathCore(root->right, expectNum, curLen, path, ans);
    }
};
posted @ 2020-03-12 11:34  Flix  阅读(118)  评论(0编辑  收藏  举报