Sum Root to Leaf Numbers - LeetCode

时间:2021-12-14 16:02:41

题目链接

Sum Root to Leaf Numbers - LeetCode

注意点

  • 不要访问空结点

解法

**解法一:递归。sum表示从root到当前节点的值的和,ret是所有路径和。如果没有左右儿子说明是叶子节点,就把sum加到ret,否则把当前的sum*10加上自己的值。**

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        int ret = 0;
        sumNumbers(root,0,ret);
        return ret;
    }
    void sumNumbers(TreeNode* root,int sum,int& ret)
    {
        if(!root) return;
        sum = sum*10+root->val;
        if(root->left) sumNumbers(root->left,sum,ret);
        if(root->right) sumNumbers(root->right,sum,ret);
        if(!root->left && !root->right) ret += sum;
    }
};

Sum Root to Leaf Numbers - LeetCode

**解法二:非递归,bfs。将自己的节点值*10加到儿子节点上,如果是叶子节点就把自己的值加到ret上(因为已经更新过了,自己的值就是路径上节点值的和)**

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        int ret = 0;
        if(!root) return ret;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            TreeNode* t = q.front();q.pop();
            if(t->left)
            {
                t->left->val = t->val*10+t->left->val;
                q.push(t->left);
            }
            if(t->right)
            {
                t->right->val = t->val*10+t->right->val;
                q.push(t->right);
            }
            if(!t->left && !t->right) ret += t->val;
        }
        return ret;
    }
};

Sum Root to Leaf Numbers - LeetCode

小结

  • 只要是遍历都有递归和非递归两种写法