题解 | #二叉树根节点到叶子节点的所有路径和#

二叉树根节点到叶子节点的所有路径和

http://www.nowcoder.com/practice/185a87cd29eb42049132aed873273e83

思路

1、深度优先,先序遍历
2、和剑指offer34(和为某一值的二叉树路径)思路一样

代码

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    int sum = 0;
    vector<vector<int>> res;


    // 前序遍历
    void helper(TreeNode* root, vector<int>& path){
        if(root==nullptr) {
            return;
        }

        path.push_back(root->val);
        if(root->left==nullptr && root->right==nullptr){
            res.push_back(path);
        }
        helper(root->left, path);
        helper(root->right, path);
        path.pop_back();

    }


    int compute_res(vector<vector<int>> res){
        int sum = 0;
        for(const auto& path:res){
            int tmp = 0;
            for(const auto& ele:path){
                tmp*=10;
                tmp += ele;
            }
            sum+=tmp;
        }
        return sum;
    }

    int sumNumbers(TreeNode* root) {
        // write code here
        vector<int> path;
        helper(root, path);
        auto ans = compute_res(res);
        return ans;
    }
};
全部评论

相关推荐

09-23 14:45
贵州大学 财务
你真的不如他呢:才四家,四十家再说吧
点赞 评论 收藏
分享
手机爱睡觉:感觉是没hc了,上次双选hr说七月份就开了招了很多人
投递网易等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务