本文主要是介绍C++ | Leetcode C++题解之第129题求根节点到叶节点数字之和,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
class Solution {
public:int sumNumbers(TreeNode* root) {if (root == nullptr) {return 0;}int sum = 0;queue<TreeNode*> nodeQueue;queue<int> numQueue;nodeQueue.push(root);numQueue.push(root->val);while (!nodeQueue.empty()) {TreeNode* node = nodeQueue.front();int num = numQueue.front();nodeQueue.pop();numQueue.pop();TreeNode* left = node->left;TreeNode* right = node->right;if (left == nullptr && right == nullptr) {sum += num;} else {if (left != nullptr) {nodeQueue.push(left);numQueue.push(num * 10 + left->val);}if (right != nullptr) {nodeQueue.push(right);numQueue.push(num * 10 + right->val);}}}return sum;}
};
这篇关于C++ | Leetcode C++题解之第129题求根节点到叶节点数字之和的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!