LeetCode_Sum Root to Leaf Numbers

一.題目

Sum Root to Leaf Numbers

  Total Accepted: 47437 Total Submissions: 156443My Submissions

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.

For example,

    1
   / \
  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

Show Tags
Have you met this question in a real interview?  
Yes
 
No

Discuss
















二.解題技巧

    這道題只是一道二叉樹的深度優先搜索的題目,在葉結點時將從根到葉結點的路徑上的結點的值組成一個十進制的數,本質上還是一道深度優先搜索的題,只是換了一種考察的形式。這道題不難,只要細心點就可以bugfree的。


三.實現代碼

#include <iostream>

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/


struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution
{
    void sumNumbers(TreeNode*root, int &Result, int &TmpResult)
    {
        if (!root)
        {
            return;
        }

        // update the TmpResult
        TmpResult = TmpResult * 10 + root->val;

        if (!root->left && !root->right)
        {
            Result += TmpResult;
        }

        if (root->left)
        {
            sumNumbers(root->left, Result, TmpResult);
        }

        if (root->right)
        {
            sumNumbers(root->right, Result, TmpResult);
        }

        // restore the TmpResult;
        TmpResult = (TmpResult - root->val) / 10;
    }

public:
    int sumNumbers(TreeNode* root)
    {
        int Result = 0;
        int TmpResult = 0;

        sumNumbers(root, Result, TmpResult);

        return Result;
    }
};



四.體會

    這道題是一道二叉樹深度優先搜索的變形題目,考察的還是二叉樹的遞歸遍歷,只是換了一種考察方式而已,並沒有多大新意。



版權所有,歡迎轉載,轉載請註明出處,謝謝微笑





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章