129. Sum Root to Leaf Numbers
来源:互联网 发布:graph cut算法原理 编辑:程序博客网 时间:2024/06/05 14:58
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which 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->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
所用到的结构体:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
递归函数如下:
class Solution {public: int getSum(TreeNode *root, int cur_sum){ // 终止条件 if (root == NULL) return 0; // 处理叶子节点 if (root->left == NULL && root->right == NULL) return cur_sum * 10 + root->val; // 递归过程 return getSum(root->left, cur_sum * 10 + root->val) + getSum(root->right, cur_sum * 10 + root->val); } // 129. Sum Root to Leaf Numbers int sumNumbers(TreeNode* root) { // 得到root为根的和 return getSum(root, 0); }}
二叉树具有天然的递归结构,这类问题要想清楚:
- 递归终止条件(包括根节点为NULL怎么处理,遇到叶子节点怎么处理);
- 递归的过程(如何定义一个递归求解过程,把一个大规模的问题缩小到相同套路的子问题,从而缩小规模);
- 一旦递归过程想清楚了,就可以假设子问题已经得到解决,进而在此基础上求解更大规模的问题。
阅读全文
0 0
- [LeetCode]129.Sum Root to Leaf Numbers
- LeetCode 129. Sum Root to Leaf Numbers
- [leetcode] 129.Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 【leetcode】129. Sum Root to Leaf Numbers
- [leetcode] 129. Sum Root to Leaf Numbers
- [LeetCode]129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers LeetCode
- [LeetCode]129. Sum Root to Leaf Numbers
- leetcode 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- Leetcode 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- LeetCode *** 129. Sum Root to Leaf Numbers
- LeetCode-129.Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 积累
- 做一个软件项目使用到的工具
- vector的reserve和resize
- JAVA8 Function、Consumer、Predicate、Supplier接口
- 关于java.lang.OutOfMemoryError: Java heap space的解决方案
- 129. Sum Root to Leaf Numbers
- 关于Java Web 使用JavaMail创建邮件和发送邮件
- 递推专题(一)HDU2044——2050
- PAT 乙级 1008
- 2.SpringBoot-环境配置
- 看图理解单链表的反转
- 【原创】Spring-boot快速入门(二)JPA数据源--转载请注明出处
- JQuery之简单下拉框
- Jmeter性能测试 入门