[LeetCode] 129. Sum Root to Leaf Numbers 解题思路

时间:2021-05-06 13:14:32

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.

问题:给定一个二叉树,树的每个节点都只包含一个数字 0-9,将根节点到叶子节点路径上的元素值组合成一个整数,求所有整数和。

这是一道深度遍历的应用。深度遍历二叉树一般是递归遍历,或者借助栈遍历。每到达一个叶子节点,都需要重新遍历一次根节点到该叶子节点路径的值,借组栈遍历可以实现满足这个需要。

     #define null_symble  -2147483648

     int sumNumbers(TreeNode* root) {

         if(root == NULL){
return ;
} list<TreeNode*> stackt;
stackt.push_back(root); int sum = ; map<TreeNode*, int> node_val; while(stackt.size() > ){
TreeNode* node = stackt.back(); if(node->val != null_symble){
node_val[node] = node->val;
node->val = null_symble;
} if (node->left != NULL && node->left->val != null_symble){
stackt.push_back(node->left);
continue;
} if(node->right != NULL && node->right->val != null_symble){
stackt.push_back(node->right);
continue;
} if(node->left == NULL && node->right == NULL){
string str = "";
list<TreeNode*>::iterator l_iter;
for(l_iter = stackt.begin(); l_iter != stackt.end(); l_iter++){
str += to_string(node_val[*l_iter]);
}
sum += stoi(str);
}
stackt.pop_back();
} return sum;
}