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

题目描述

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

解题思路

基本路线仍未进行二叉树遍历,只不过在路过一个节点时需要对该节点走过的路径长度进行统计。

C++代码实现:

/*
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<vector<int> > result; 
        if (root==NULL){
              return result;
          }
        int alreadyNum=0;
        vector<int> path;
        findsubway(result,path,root,expectNumber,alreadyNum);
        return result;
    }
    void findsubway(vector<vector<int> >& result,vector<int>& path,TreeNode* root,int expectNumber,int& alreadyNum){
        alreadyNum+=root->val;
        path.push_back(root->val);
        //判断是否是叶子节点
        bool isLeaf=(root->left==NULL)&& (root->right==NULL);
        if(isLeaf){
            if(alreadyNum==expectNumber){
                vector<int> tmp(path);
                //是满足要求的路径,存入
                result.push_back(tmp);
            }
        }else{
            //如果遇见当前节点路径已经比期望值要大,则跳过此子树
            if(alreadyNum<expectNumber){
                if(root->left!=NULL){
                    findsubway(result,path,root->left,expectNumber,alreadyNum);    
                }
                if(root->right!=NULL){
                    findsubway(result,path,root->right,expectNumber,alreadyNum);    
                }   
            }
        }
        alreadyNum-=root->val;
        path.pop_back();
    }
};

 

posted @ 2019-10-05 20:08  fancy_li  阅读(125)  评论(0编辑  收藏  举报