Leetcode Note: Sum Root to Leaf Numbers

Source: Internet
Author: User

Leetcode Note: Sum Root to Leaf Numbers

I. Description

Given a binary tree containing digits from 0-9 only, each root-to-leaf path cocould 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 path1->2Represents the number12.
The root-to-leaf path1->3Represents the number13.

Returnsum = 12 + 13 = 25.

Ii. Question Analysis

This question is just a binary tree deep Priority Search question. When the leaf node points, the node values from the root to the leaf node path constitute a decimal number, in essence, it is still a deep-first search question.

Iii. Sample Code

#include 
  
   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;    }};
  

Iv. Summary

This question is a problem of deformation of binary tree deep priority search. It is the recursive traversal of binary tree, but it is just a different method.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.