Tree Summing
Tree Summing |
Background
LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the oldest languages currently being used. Lists, which are the fundamental data structures in LISP, can easily be adapted to represent other important data structures such as trees.
This problem deals with determining whether binary trees represented as LISP S-expressions possess a certain property.
The Problem
Given a binary tree of integers, you are to write a program that determines whether there exists a root-to-leaf path whose nodes sum to a specified integer. For example, in the tree shown below there are exactly four root-to-leaf paths. The sums of the paths are 27, 22, 26, and 18.
Binary trees are represented in the input file as LISP S-expressions having the following form.
empty tree ::= ()tree ::= empty tree
(integer tree tree)
The tree diagrammed above is represented by the expression (5 (4 (11 (7 () ()) (2 () ()) ) ()) (8 (13 () ()) (4 () (1 () ()) ) ) )
Note that with this formulation all leaves of a tree are of the form (integer () () )
Since an empty tree has no root-to-leaf paths, any query as to whether a path exists whose sum is a specified integer in an empty tree must be answered negatively.
The Input
The input consists of a sequence of test cases in the form of integer/tree pairs. Each test case consists of an integer followed by one or more spaces followed by a binary tree formatted as an S-expression as described above. All binary tree S-expressions will be valid, but expressions may be spread over several lines and may contain spaces. There will be one or more test cases in an input file, and input is terminated by end-of-file.
The Output
There should be one line of output for each test case (integer/tree pair) in the input file. For each pairI,T (I represents the integer, T represents the tree) the output is the stringyes if there is a root-to-leaf path in T whose sum is I andno if there is no path in T whose sum is I.
Sample Input
22 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()())))) 20 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()())))) 10 (3 (2 (4 () () ) (8 () () ) ) (1 (6 () () ) (4 () () ) ) ) 5 ()
Sample Output
yes no yes no
这道题给你一个值n和一棵整数二叉树的先序遍历的形式 ( value ( left subtree) ( right subtree))的形式,判断是否存在某条路径的节点和等于n。我用的是最笨最麻烦的方法,先根据表达形式复原二叉树,再遍历一遍各个路径。
#include <iostream> #include <stack> #include <cstdio> #include <cmath> using namespace std; int n; struct Node { int data; Node * left, * right; }; typedef Node * Position; Position & buildTree( char * str, int s, int e) { Position root = NULL; if( str[s+1] == ')') return root; root = new Node; root->data = 0; stack<int> st; int sign = 0; if( str[s+1] == '-') { sign = 1; s++;} int i; for( i = s+1; (str[i]<='9' && str[i]>='0'); i++) st.push( str[i]-'0'); int cnt = 0; while( !st.empty()){ root->data += pow( 10, cnt++)*st.top(); st.pop(); } if( sign) root->data *=-1; int ls = i; stack<char> chS; chS.push( str[i]); do{ i++; if( str[i] == '(') chS.push( str[i]); if( str[i] == ')') chS.pop(); }while( !chS.empty()); root->left = buildTree( str, ls, i); root->right = buildTree( str, i+1, e-1); return root; } int getSum( int sum, const Position & t) { if( !t->left && !t->right) return sum == n; bool ans = false; if( t->left) ans = getSum( sum+t->left->data, t->left); if( ans) return ans; if( t->right) ans = getSum( sum+t->right->data, t->right); return ans; } void makeEmpty( const Position & t) { if( !t) return; makeEmpty( t->left); makeEmpty( t->right); delete t; } char str[50000]; int main() { while( cin >> n){ int i = 0; int leftPar = 0,rightPar = 0; char ch; while( scanf("%c", &ch)){ if( ch == '(') leftPar++; if( ch == ')') rightPar++; if( ch != '\n' && ch != ' ') str[i++] = ch; if( leftPar == rightPar && leftPar) break; } str[i] = 0; Position root = NULL; root = buildTree( str, 0, i-1); if( !root) cout << "no" << endl; else if( getSum( root->data, root)) cout << "yes" << endl; else cout << "no" << endl; makeEmpty( root); } return 0; }
网上看高手的解题报告,发现可以用递归边输入边处理,代码又快又短-.- 还看到了有cin.clear()这种好东西
代码来自:http://www.cnblogs.com/devymex/archive/2010/08/10/1796854.html#include <iostream> #include <string> using namespace std; //递归扫描输入的整棵树 bool ScanTree(int nSum, int nDest, bool *pNull) { static int nChild; //略去当前一级前导的左括号 cin >> (char&)nChild; //br用于递归子节点的计算结果,bNull表示左右子是否为空 bool br = false, bNull1 = false, bNull2 = false; //如果读入值失败,则该节点必为空 if (!(*pNull = ((cin >> nChild) == 0))) { //总和加上读入的值,遍例子节点 nSum += nChild; //判断两个子节点是否能返回正确的结果 br = ScanTree(nSum, nDest, &bNull1) | ScanTree(nSum, nDest, &bNull2); //如果两个子节点都为空,则本节点为叶,检验是否达到目标值 if (bNull1 && bNull2) { br = (nSum == nDest); } } //清除节点为空时cin的错误状态 cin.clear(); //略去当前一级末尾的右括号 cin >> (char&)nChild; return br; } //主函数 int main(void) { bool bNull; //输入目标值 for (int nDest; cin >> nDest;) { //根据结果输出yes或no cout << (ScanTree(0, nDest, &bNull) ? "yes" : "no") << endl; } return 0; }