Leetcode Sum Root to Leaf Numbers

来源:互联网 发布:c语言二分法求方程例题 编辑:程序博客网 时间:2024/03/29 01:11

还是dfs。跟Minimum Depth of Binary Tree以及Maximum Depth of Binary Tree很像。

/** * 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) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        sum = 0;        if(!root)   return sum;        dfs(root, 0);        return sum;    }    void dfs(TreeNode *root, int n){        if(!root)   return ;        if(!root->left && !root->right){            sum += (n*10 + root->val);            return ;        }        dfs(root->left, n*10+root->val);        dfs(root->right, n*10+root->val);    }    int sum;};


原创粉丝点击