二叉树中的根节点到叶子节点各个路径求和

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode *root) {
        int sum=0;
        int allsum=0;
        if(root){
        findpath(root,sum,allsum);
        }
        return allsum;
    }
    void  findpath(TreeNode *root,int sum, int &allsum){
        if(root==NULL){
            return ;
        }
         sum=sum*10 + root->val;
        if(root->left==NULL && root->right==NULL){
          
             allsum+=sum;
        }
        if(root->left!=NULL){       
            findpath(root->left,sum,allsum);
        }
        if(root->right!=NULL){
            findpath(root->right,sum,allsum);
        }
    }
};

2 根节点到某个值到路径

    void ownFindPath(TreeNode * root, int expect, list<TreeNode *> tempPath) {  // 发现根节点到某个路径
        if (root == NULL) {
            return ;
        }
        tempPath.push_back(root);
        if (root->left == NULL && root->right == NULL && root->val == expect) {
            res.push_back(tempPath);
        }
        if (root->left) {
            ownFindPath(root->left, expect, tempPath);
        }
        if (root->right) {
            ownFindPath(root->right, expect, tempPath);
        }
    }

猜你喜欢

转载自blog.csdn.net/u010325193/article/details/86190182