LeetCode:Sum Root to Leaf Numbers

时间:2021-08-25 15:57:44

题目链接 

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 /**
 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     struct Qnode
13     {
14       int sum_;
15       TreeNode* p_;
16       Qnode(int s, TreeNode *p):sum_(s),p_(p){}
17       Qnode(){}
18     };
19     int sumNumbers(TreeNode *root) {
20         // IMPORTANT: Please reset any member data you declared, as
21         // the same Solution instance will be reused for each test case.
22         if(root == NULL)return 0;
23         queue<Qnode> myqueue;
24         myqueue.push(Qnode(root->val, root));
25         int res = 0;
26         while(myqueue.empty() == false)
27         {
28             Qnode tmp = myqueue.front();
29             myqueue.pop();
30             if(tmp.p_->left == NULL && tmp.p_->right == NULL)
31                 res += tmp.sum_;
32             else
33             {
34                 if(tmp.p_->left != NULL)
35                     myqueue.push(Qnode(tmp.sum_*10 + tmp.p_->left->val, tmp.p_->left));
36                 if(tmp.p_->right != NULL)
37                     myqueue.push(Qnode(tmp.sum_*10 + tmp.p_->right->val, tmp.p_->right));
38             }
39         }
40         return res;
41     }
42 };

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3421697.html