#include <iostream> #include <stdio.h> #include <queue> using namespace std; typedef struct lnode { int data; struct lnode *left, *right; }node; void createTree(node * &root, int x) { if (root == NULL) { node * p = new node; p->data = x; p->left = p->right = NULL; root = p; } else { if (x <= root->data) createTree(root->left, x); else createTree(root->right, x); } } void orderTraverse(node * root) { if (root != NULL) { orderTraverse(root->left); cout<<root->data<<" "; orderTraverse(root->right); } } //non-recursion to order traverse the tree void orderTraverse2(node * root) { stack<node *> treeStack; do { //visit all the left nodes, and store them in the stack while (root != NULL) { treeStack.push(root); root = root->left; } //pop one left node, print it and visit its right node if (!treeStack.empty()) { root = treeStack.top(); treeStack.pop(); cout<<root->data<<" "; root = root->right; } } while (!treeStack.empty() || root != NULL); } //get the height of the tree int getTreeHeight(node * root) { if (root != NULL) { int x = getTreeHeight(root->left); int y = getTreeHeight(root->right); if (x > y) return x+1; else return y+1; } } //output the tree element by layer void layeroutput(node * root) { queue<node *> nodeQ; if (root != NULL) nodeQ.push(root); while(!nodeQ.empty()) { node * a_node = nodeQ.front(); nodeQ.pop(); cout<<a_node->data<<" "; if (a_node->left != NULL) nodeQ.push(a_node->left); if (a_node->right != NULL) nodeQ.push(a_node->right); } } //print all the paths, where sum of the value is n void findPath(node * root, int n) { static int sum = 0; static vector<node *> m_path; sum += root->data; m_path.push_back(root); //print result if (sum == n && root->left == NULL && root->right == NULL) { cout<<"find the path: "; for (vector<node *>::iterator it = m_path.begin(); it < m_path.end(); it++) { cout<<(*it)->data << " "; } cout<<endl; } if (root->left) findPath(root->left, n); if (root->right) findPath(root->right, n); sum -= root->data; m_path.pop_back(); } int main(void) { int x; node * root = NULL; while (scanf("%d", &x) != EOF) { createTree(root, x); } orderTraverse(root); cout<<"height of the tree: "<<getTreeHeight(root)<<endl; layeroutput(root); }
树 --- 创建+中序遍历+按层次输出+计算树的高度+输出和为n的所有路径
最新推荐文章于 2014-01-08 22:45:58 发布