【剑指Offer】二叉树中和为某一值的路径

问题描述

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

算法分析

  1. 如果 root 等于 输入数,将root放在返回数组里返回;如果root大于输入数,返回空值;
    如果root小于输入数,将root放在数组里,输入数自减root,一同随root的子树递归;
  2. 如果输入数为0了且左右子树都为空,即为叶子节点,则这条路径可行,返回数组;
    如果 root 没有子树了,同时输入数还没为0,说明此路不通,返回NULL。

代码实现

/*
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, intexpectNumber) {
        vector<vector<int> > result;
        if(root == NULL) {
            return result;
        }
        int data = root->val;
        if(expectNumber < data) {
            return result;
        }
 
        elseif(expectNumber == data) {
            vector<int> x;
            x.push_back(data);
            result.push_back(x);
        }
 
        else{
            expectNumber -= data;
            bool left = findPath(&result, root->left, expectNumber);
            bool right = findPath(&result, root->right, expectNumber);
            if( left || right ) {
                for(int i = 0; i < result.size(); i++) {
                    result[i].push_back(data);
                    reverse(&(result[i]));
                }
            }
        }
        return result;
    }
 
    bool findPath(vector<vector<int> >* result, TreeNode* root, intexpectNumber) {
        if(root == NULL && expectNumber == 0) {
            return true;
        }
        elseif(root == NULL) {
            return false;
        }
 
        int data = root->val;
 
        if(expectNumber < data) {
            return false;
        }
 
        elseif(expectNumber == data&& root->left == NULL && root->right == NULL) {
            vector<int> x;
            x.push_back(data);
            result->push_back(x);
        }
 
        else{
            expectNumber -= data;
            vector<vector<int> > left;
            bool bLeft = findPath(&left, root->left, expectNumber);
            if(bLeft) {
                for(inti = 0; i < left.size(); i++) {
                    left.at(i).push_back(data);
                    result->push_back(left[i]);
                }
            }
            vector<vector<int> > right;
            bool bRight = findPath(&right, root->right, expectNumber);
            if(bRight) {
                for(int i = 0; i < right.size(); i++) {
                    right.at(i).push_back(data);
                    result->push_back(right[i]);
                }
            }
        }
 
        return result;
    }
 
    void reverse(vector<int>* v) {
        int size = v->size();
        int half = size / 2;
        for(inti = 0; i < half; i++) {
            int tmp = v->at(i);
            v->at(i) = v->at(size - i - 1);
            v->at(size - i - 1) = tmp;
        }
    }
};