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