LeetCode :: Sum Root to Leaf Numbers [tree、dfs]
2014-07-17 22:24
267 查看
Given a binary tree containing digits from
each root-to-leaf path could represent a number.
An example is the root-to-leaf path
the number
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 =
从根节点开始,dfs的思路,其实也就是postorder(先序遍历),遍历路径上的值每次乘以基数10,过程很简单,代码如下:
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.
从根节点开始,dfs的思路,其实也就是postorder(先序遍历),遍历路径上的值每次乘以基数10,过程很简单,代码如下:
class Solution { public: int sum; void dfs(TreeNode *root, int pre){ if (root == NULL) return; int current = root->val + 10 * pre; if (root->left == NULL && root->right == NULL){ sum += current; return; } if (root->left) dfs(root->left, current); if (root->right) dfs(root->right, current); } int sumNumbers(TreeNode *root) { sum = 0; dfs(root, 0); return sum; } };
相关文章推荐
- LeetCode :: Sum Root to Leaf Numbers [tree、dfs]
- [leetcode][tree][dfs] Sum Root to Leaf Numbers
- Leetcode dfs Sum Root to Leaf Numbers
- leetcode_Sum Root to Leaf Numbers _DFS_中等难度
- leetcode -- Sum Root to Leaf Numbers -- dfs
- Posts Tagged 【tree && dfs】Sum Root to Leaf Numbers
- 129.leetcode Sum Root to Leaf Numbers(medium)[深度遍历DFS]
- LeetCode[Tree]: Sum Root to Leaf Numbers
- leetcode:Sum Root to Leaf Numbers (二叉树的DFS)
- leetcode_129题——Sum Root to Leaf Numbers(基于DFS的递归)
- [LeetCode] Sum Root to Leaf Numbers dfs,深度搜索
- 【leetcode】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
- [Leetcode 39] 129 Sum Root to Leaf Numbers
- leetcode Sum Root to Leaf Numbers(所有路径之和)
- LeetCode-Sum Root to Leaf Numbers
- leetcode之Sum Root to Leaf Numbers