Sum Root to Leaf Numbers深度优先计算路径和
2014-11-20 14:42
375 查看
Given a binary tree containing digits from
An example is the root-to-leaf path
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path
The root-to-leaf path
Return the sum = 12 + 13 =
Hide Tags
Tree Depth-first Search
0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path
1->2->3which represents the number
123.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path
1->2represents the number
12.
The root-to-leaf path
1->3represents the number
13.
Return the sum = 12 + 13 =
25.
Hide Tags
Tree Depth-first Search
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: int sum; public: void dfs(TreeNode *root,int num){ if(root==NULL) return; if(root->left==NULL && root->right==NULL){ num=num*10+root->val; sum=sum+num; return; } num=num*10+root->val; dfs(root->left,num); dfs(root->right,num); } int sumNumbers(TreeNode *root) { sum=0; dfs(root,0); return sum; } };
相关文章推荐
- [LeetCode] Sum Root to Leaf Numbers dfs,深度搜索
- 129.leetcode Sum Root to Leaf Numbers(medium)[深度遍历DFS]
- leetcode Sum Root to Leaf Numbers(所有路径之和)
- 从根到叶的每条路径构成一个数,求这些数的和(Sum Root to Leaf Numbers)
- leetcode Sum Root to Leaf Numbers 二叉树所有叶节点的路径和
- leetcode Sum Root to Leaf Numbers(所有路径之和)
- Sum Root to Leaf Numbers 求路径之和
- Leetcode 129. Sum Root to Leaf Numbers 计算路径和 解题报告
- LeetCode | Sum Root to Leaf Numbers(所有根结点到叶节点路径和的和)
- 【二叉树的递归】07路径组成数字的和【Sum Root to Leaf Numbers】
- Sum Root to Leaf Numbers 求所有二叉树根到叶子节点路径之和 @LeetCode
- Sum Root to Leaf Numbers
- leetcode: Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- LeetCode之sum root to leaf numbers
- [leetcode] Sum Root to Leaf Numbers
- [LeetCode] Sum root to leaf numbers
- leetcode:Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- 【leetcode】Sum Root to Leaf Numbers