【Leetcode】【Medium】Sum Root to Leaf Numbers (未完成)

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.

解题思路1:

以按层遍历的思维,当要深入下一层时,将当前层累加的value值乘以10,并带入下一层继续运算,直到运算到叶子结点。之后累加所有叶子结点。

使用递归很容易实现:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int sumNumbers(TreeNode *root) {
13         if (!root)
14             return 0;
15         
16         if (!root->left && !root->right) 
17             return root->val;
18         else 
19             return sumLeaf(root->left, root->val) + 
20                 sumLeaf(root->right, root->val);
21     }
22     
23     int sumLeaf(TreeNode *node, int cur_sum) {
24         if (!node) 
25             return 0;
26         
27         if (!node->left & !node->right)
28             return cur_sum * 10 + node->val;
29         else
30             return sumLeaf(node->left, cur_sum * 10 + node->val) +
31                 sumLeaf(node->right, cur_sum * 10 + node->val);
32     }
33 };

解题思路2:

递归的使用,造成程序运行慢。为了不使用递归可以按照二叉树先序遍历的方法。

代码:

原文地址:https://www.cnblogs.com/huxiao-tee/p/4229981.html