LeetCode: Sum Root to Leaf Numbers

来源:互联网 发布:wkwebview 的js调用oc 编辑:程序博客网 时间:2024/05/27 20:31

思路:还是深度搜索树,当前节点如果是叶子节点,则计算出从根到叶子节点表示的数(这个数在路径中一直动态存储),加到总和中。

code:

class Solution {public:    void dfs(TreeNode *p,int &sum,int curNum){        if(p->left == NULL && p ->right == NULL){            curNum *= 10;            curNum += p->val;            sum += curNum;            return;        }        if(p->left)            dfs(p->left,sum,curNum*10+p->val);        if(p->right)            dfs(p->right,sum,curNum*10+p->val);    }    int sumNumbers(TreeNode *root) {        if(root){            int ret = 0;            dfs(root,ret,0);            return ret;        }        return 0;    }};


0 0
原创粉丝点击