Leetcode P0129"Sum Root to Leaf Numbers" 题解

2020/09/11 Leetcode

博文中会简要介绍Leetcode P0129题目分析及解题思路。

“Sum Root to Leaf Numbers”这道题相对比较简单,本质上就是深度优先搜索,每次探索到叶子结点,然后将叶子结点组成的整数加到最终的和上。

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.

Note: A leaf is a node with no children.

以下是Java的题解代码实现。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int sumNumbers(TreeNode root) {
        if (root == null)
            return 0;
        
        this.dfs(root, 0);
        return this.sum;
    }
    
    private int sum = 0;
    
    private void dfs(TreeNode curr, int prevSum) {
        if (curr.left == null && curr.right == null) {
            prevSum = prevSum*10+curr.val;
            sum += prevSum;
        }
        
        if (curr.left != null)
            this.dfs(curr.left, prevSum*10+curr.val);
        if (curr.right != null)
            this.dfs(curr.right, prevSum*10+curr.val);
    }
}

以下是C++的题解代码实现。对于C++代码风格,后续将尽量遵循Google开源风格,包括命名规范等。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        if (!root)
            return 0;
        
        this->_Dfs(root, 0);
        return this->sum_;
    }
    
private:
    int sum_ = 0;
    
    void _Dfs(TreeNode *curr, int prev_sum) {
        if (!curr->left && !curr->right) {
            prev_sum = prev_sum*10+curr->val;
            this->sum_ += prev_sum;
        }
        
        if (curr->left)
            this->_Dfs(curr->left, prev_sum*10+curr->val);
        if (curr->right)
            this->_Dfs(curr->right, prev_sum*10+curr->val);
    }
};

Search

    Table of Contents