C++//树结构递归不解之处
- C/C++ code
#include <iostream>#include <iomanip>using namespace std;typedef int T;struct Node{ T data; Node* left; Node* right; Node(const T& d):data(d),left(),right(){}};class Bst{private: Node* root; int sz; typedef Node* tree; void insert(Node*p,tree&t) { if(p==NULL) return; if(t==NULL) t=p; else if(p->data>t->data) insert(p,t->right); else insert(p,t->left); } int high(tree& t) { if(t==NULL) return 0; int lh = high(t->left); int rh = high(t->right); return (lh<rh?lh:rh)+1;//树结构三层。递归三层时,if判断,return 0时,int lh=high(t->left);递归完(没走到return (lh<rh?lh:rh)+1)吧? //递归下一句前,lh的值为啥是0?为啥不是垃圾值? } void print(tree&t,int s,char c) { if(t==NULL) return; print(t->right,s+3,'/'); cout << setw(s) << c << t->data <<endl; print(t->left,s+3,'\\'); }public: Bst():root(),sz(){} ~Bst(){} void insert(const T& d) { Node* pn = new Node(d); insert(pn,root); sz++; } int high() { return high(root); } void print() { print(root,0,'*'); }};int main(){ Bst t; t.insert(5); t.insert(3); t.insert(2); t.insert(4); t.insert(8); t.insert(6); t.insert(9); cout << t.high() <<endl; t.print();}
[解决办法]