129. 求根节点到叶节点数字之和 - 力扣(LeetCode)
深度优先遍历dfs;
遍历到叶子节点就返回;
class Solution {
public:
int sumNumbers(TreeNode* root) {
return dfs(root, 0);
}
int dfs(TreeNode* root,int prenum)
{
if(root == nullptr)
{
return 0;
}
int sum = prenum * 10 + root->val;
if(root->left == nullptr && root->right == nullptr)
{
return sum;
}
return dfs(root->left, sum) + dfs(root->right, sum);
}
};
广度优先遍历
两个队列,先进先出queue;
一个是存root节点,一个存val;
两个队列同时push,同时pop
class Solution {
public:
int sumNumbers(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int sum = 0;
queue<TreeNode*> treenode;
queue<int> treenum;
treenode.push(root);
treenum.push(root->val);
while(!treenode.empty())
{
TreeNode* node = treenode.front();
int num = treenum.front();
treenum.pop();
treenode.pop();
TreeNode* left = node->left;
TreeNode* right = node->right;
if(left == nullptr && right == nullptr)
{
sum += num;
}
else
{
if(left != nullptr)
{
treenode.push(left);
treenum.push(num * 10 + left->val);
}
if(right != nullptr)
{
treenode.push(right);
treenum.push(num * 10 + right->val);
}
}
}
return sum;
}
};