Cracking the coding interview 4.8

Source: Internet
Author: User

You are given a binary tree in which each node contains a value. design an algorithm to print all paths which sum up to that value. note that it can be any path in the tree-it does not have to start at the root.

Ideas:

Since the beginning of the path is not necessarily in the root, it is not enough to find all the paths starting from the root. Each node may start or end. If any node is used as the end node, It is pushed to the root node. If there is a sum of values in the path, it is a satisfying path, but it cannot be stopped until it is pushed to the root node, because the reverse push sequence may be 2 + 3-1 + 1. If the value is 5, 2 + 3 is satisfied, but 2 + 3-1 + 1 is also satisfied, therefore, we have to roll it down to the root to find all the paths.

Void func (node * n, int * Buf, int level, int sum) // n is the end node. Buf stores the key from this node to each root node, level is depth, sum is required and {If (n = NULL) {return;} Buf [level] = N-> key; int temp = sum; for (INT I = level; I> = 0; I --) {temp-= Buf [I]; If (temp = 0) {for (Int J = I; j <level; j ++) {printf ("% d,", Buf [J]);} printf ("% d \ n ", buf [level]) ;}} func (n-> left, Buf, level + 1, sum); func (n-> right, Buf, level + 1, sum );}

 

Cracking the coding interview 4.8

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.