标签:tree depth-first search leetcode
题目:
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
.
观察题目给的返回值是int,可知测试集的树高度不超过10,这道题我们可以不考虑溢出的情况,如果没有题目限定,需要考虑。用递归来实现,本质上就是先序遍历。考虑递归条件和结束条件。我们的目标是把从根到叶子结点的所有路径得到的整数累加起来。递归条件就是把当前sum值乘以10再加上当前节点的值,传给下一个函数(123 = 12 *10 + 3),随着递归的深度,我们最顶端的数值会不断乘以10,这样就不需要计算这条路径的深度再看10的幂是多少了。进行递归,我们把左右子树的总和相加。结束条件是,如果一个节点的叶子,我们将目前的累加结果乘以10再加叶子节点值,返回后加到最终综合种。如果节点时空节点,而不是叶子结点,不需要加到结果中,返回0.
复杂度:先序遍历则,时间复杂度O(N),空间是栈大小,O(log(n))
树的题目在LeetCode中还是有比较大的比例的,不过除了基本的递归和非递归的遍历之外,其他大部分题目都是用递归方式来求解特定量.递归法是解决树的问题最常用的办法。
AC Code:
/** * 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) { return sumNumbers_helper(root, 0); } private: int sumNumbers_helper(TreeNode* root, int x) { if(root == NULL) return 0; if(root->left == NULL && root->right == NULL) { return 10 * x + root->val; } return sumNumbers_helper(root->left, 10*x + root->val) + sumNumbers_helper(root->right, 10*x + root->val); } };
[C++]LeetCode: 94 Sum Root to Leaf Numbers (先序遍历)
标签:tree depth-first search leetcode
原文地址:http://blog.csdn.net/cinderella_niu/article/details/42713809