1. 程式人生 > >劍指offer第二十四題【二叉樹中和為某一值的路徑】c++實現

劍指offer第二十四題【二叉樹中和為某一值的路徑】c++實現

題目描述

輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。

先序遍歷二叉樹,用一個數組記錄當前路徑,如果遍歷到葉子節點就進行判斷是否和給定值相等。

class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if(root==NULL){
            return res;
        }
        preorder(root,expectNumber);
        return res;
    }
    void preorder(TreeNode *root,int expectNumber) {
        path.push_back(root->val);
        if(!root->left&&!root->right){
            int sum=0;
            for(int i=0;i<path.size();i++){
                sum+=path[i];
            }
            if(sum==expectNumber){
                res.push_back(path);
            }
        }
        if(root->left)
            preorder(root->left,expectNumber);
        if(root->right)
            preorder(root->right,expectNumber);
        path.erase(path.end()-1);

    }
    vector<vector<int> > res;
    vector<int> path;
};