# Leetcode first fl _ Sum Root to Leaf Numbers

Source: Internet
Author: User

The problem about the tree is still relatively simple. recursive and recursive will be handed over for 10 thousand years. No, you can also traverse and traverse for 10 thousand years. Haha. General problems can be solved elegantly with the help of the pre-and post-sequence sequences. recursion is often used during traversal. If the sequence is a sequence, queue may be used.

In fact, there is nothing to say about this question. In front of the median, the fathers must first traverse the data in order to update the sum of the data on the leaves. Here we will talk about the more interesting questions a lab student has encountered during the interview. It is known that the two nodes on the tree have the relationship between the ancestor and the younger generation. How can we only use one traversal to dye all the nodes between them in red? The answer is post-order traversal. Why? In my opinion, what is the essence of a tree? It is an ethical question. A father can have many children, and a child can have only one father. What does this mean? There are many ways to go from top to bottom, but the path to go up must be unique. I think this is the biggest difference between a tree and a graph, and it is much simpler than a graph. Since we can only dye the paths in red and use only one traversal, it must be done when we determine the path. Of course, this question is not complete yet. There are still many details about how to dye it. I just want to convey my understanding of traversal.

Ac code:

`Void sumAll (TreeNode * root, int & sum, int tpNum) {tpNum = tpNum * 10 + root-> val; if (! Root-> left &&! Root-> right) sum + = tpNum; if (root-> left) sumAll (root-> left, sum, tpNum); if (root-> right) sumAll (root-> right, sum, tpNum);} class Solution {public: int sumNumbers (TreeNode * root) {if (root = NULL) return 0; int res = 0; sumAll (root, res, 0); return res ;}};`

Related Keywords:

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.