Sum Root to Leaf Numbers - LeetCode

題目連接

Sum Root to Leaf Numbers - LeetCodecode

注意點

  • 不要訪問空結點

解法

**解法一:遞歸。sum表示從root到當前節點的值的和,ret是全部路徑和。若是沒有左右兒子說明是葉子節點,就把sum加到ret,不然把當前的sum*10加上本身的值。**blog

/**
 * 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;
    }
};

**解法二:非遞歸,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;
    }
};

小結

  • 只要是遍歷都有遞歸和非遞歸兩種寫法
相關文章
相關標籤/搜索