http://oj.leetcode.com/problems/sum-root-to-leaf-numbers/
// Tried many times to get accepted
// Take care:
// 1. root is NULL
// 2. node with one child
// 3. leaf
class Solution {
public:
int sumNumbers(TreeNode *root, int last){
if(root->left==NULL&&root->right==NULL) return last*10+root->val;
else if(root->left==NULL) return sumNumbers(root->right,last*10+root->val);
else if(root->right==NULL) return sumNumbers(root->left,last*10+root->val);
else return sumNumbers(root->left,last*10+root->val)+sumNumbers(root->right,last*10+root->val);
}
int sumNumbers(TreeNode *root) {
// Take care of the case that root is NULL
if(root==NULL) return 0;
else return sumNumbers(root,0);
}
};
本文介绍了一个LeetCode上的题目解决方案:求二叉树中从根节点到叶节点的所有路径数值之和。通过递归算法遍历每个节点,并在到达叶节点时返回路径值。
201

被折叠的 条评论
为什么被折叠?



