二叉樹的路徑和

問題描述:

給定一個二叉樹,找出所有路徑中各節點相加總和等於給定 目標值 的路徑。

一個有效的路徑,指的是從根節點到葉節點的路徑。

解題思路:

對每條路徑進行加和,與給定的值比較,若相等,加到向量中。

代碼:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root the root of binary tree
     * @param target an integer
     * @return all valid paths
     */
    vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
          vector<vector<int> >paths;
        vector<int>path;
        vector<int>::iterator it;
        if(root==NULL){
            return paths;
        }
        else {
            def(root,paths,path,target);
            return paths;
        }
    }
    void def(TreeNode*root,vector<vector<int> >&ps,vector<int>p,int target){
        p.push_back(root->val);
        vector<int>::iterator itp;
        if(root->left==NULL&&root->right==NULL){
                int flag=0;
            for(itp=p.begin();itp!=p.end();itp++){
                flag+=*itp;
            }
            if(flag==target){
                ps.push_back(p);
            }
        }
        if(root->left!=NULL){
            def(root->left,ps,p,target);
        }
        if(root->right!=NULL){
            def(root->right,ps,p,target);
        }
        // Write your code here
    }
};

感想:

注意思路

發佈了49 篇原創文章 · 獲贊 0 · 訪問量 5005
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章