二叉樹中和爲某一值的路徑

題目描述

輸入一顆二叉樹的根節點和一個整數,打印出二叉樹中結點值的和爲輸入整數的所有路徑。路徑定義爲從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中,數組長度大的數組靠前)

/*
struct TreeNode {
 int val;
 struct TreeNode *left;
 struct TreeNode *right;
 TreeNode(int x) :
   val(x), left(NULL), right(NULL) {
 }
};*/
class Solution {
public:
       vector<int>  yiwei;
        vector<vector<int>> erwei;
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
 
        if(root==NULL)
        {
            return erwei;
        }
        yiwei.push_back(root->val);
        if(root->left==NULL&&root->right==NULL&&root->val==expectNumber)
        {
            erwei.push_back(yiwei);
        }
        if(root->left!=NULL && root->val<expectNumber)
        {
            FindPath(root->left,expectNumber- root->val )  ;        
        }
        if(root->right!=NULL&&root->val<expectNumber)
        {
           FindPath(root->right,expectNumber- root->val)  ;        
        }
        yiwei.pop_back();
        return erwei;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章