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 /** 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 preorder(root, 0); 14 return ans; 15 } 16 17 void preorder(TreeNode* root, int num) { 18 if( !root ) return ; 19 num = num*10 + root->val; //root到当前节点所代表的数字 20 if( !root->left && !root->right ) ans += num; //若为叶节点,则加入结果ans中 21 preorder(root->left, num); //先序遍历左子树 22 preorder(root->right, num); //先序遍历右子树 23 } 24 25 private: 26 int ans = 0; 27 };
方法二:层次遍历这棵树,并记录从root到该节点所代表的数字,当碰到当前节点为叶节点的时候,就直接将叶节点代表的数字加入到结果值中,代码如下:
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 Node { 13 TreeNode* cur; 14 int num; //当前节点所代表的数字 15 Node(TreeNode* _cur, int _num) : cur(_cur), num(_num) {} 16 }; 17 18 public: 19 int sumNumbers(TreeNode *root) { 20 if( !root ) return 0; 21 int ans = 0; 22 queue<Node> qt; 23 qt.push( Node(root, root->val) ); //放入根节点及根节点所代表的num 24 while( !qt.empty() ) { 25 Node node = qt.front(); 26 qt.pop(); 27 if( !node.cur->left && !node.cur->right ) ans += node.num; //每取一个节点,判断是否是叶节点,是则将num加入结果中 28 else { 29 if( node.cur->left ) //存在左节点,就将其加入队列中,并计算好其代表的值 30 qt.push( Node(node.cur->left, node.num*10 + node.cur->left->val) ); 31 if( node.cur->right ) //右节点同上 32 qt.push( Node(node.cur->right, node.num*10 + node.cur->right->val) ); 33 } 34 } 35 return ans; 36 } 37 };