int getcol(int rx,int ry) { int col; float d=getdepth(rx,ry); if (d==back) col=0; else { float diff=2.0*d-getdepth(rx-1,ry)-getdepth(rx,ry-1); col=chop(128.0-diff*4800.0,0,255); } return col; }
bool getdepth(TreeNode *root, int *d) { if (!root) { *d = 0; return 1; } int left; int right; bool res = getdepth(root->left, &left) && getdepth(root->right, &right); res = res && (abs(left - right)) <= 1; *d = max(left, right) +1; return res; }
Result getdepth(TreeNode *root){ Result re; if (root == NULL){ re.height = 0; re.isbalanced = true; return re; } Result left = getdepth(root->left); Result right = getdepth(root->right); if (left.isbalanced && right.isbalanced && abs(left.height - right.height)<=1){ re.height = (left.height > right.height ? left.height:right.height)+1; re.isbalanced = true; return re; } re.height = (left.height > right.height ? left.height:right.height)+1; re.isbalanced = false; return re; }
main() { char device[10], *p; float x, y, tdir = TRANS; int but, nplanes; int i, n; char buf[10][128]; fprintf(stderr,"Enter output device: "); gets(device); prefposition(50, 50); vinit(device); window(-800.0, 800.0, -800.0, 800.0, -800.0, 800.0); lookat(0.0, 0.0, 1500.0, 0.0, 0.0, 0.0, 0.0); makeobj(1); makepoly(); rect(-CUBE_SIZE, -CUBE_SIZE, CUBE_SIZE, CUBE_SIZE); closepoly(); closeobj(); if ((nplanes = getdepth()) == 1) makecubes(0); makecubes(1); backface(1); if (backbuffer() < 0) { vexit(); fprintf(stderr, "lcube: device doesn't support double buffering.\n"); exit(0); } while((but = slocator(&x, &y)) != 44) { pushmatrix(); rotate(100.0 * x, 'y'); rotate(100.0 * y, 'x'); color(BLACK); clear(); callobj(3); if (nplanes == 1) callobj(2); popmatrix(); swapbuffers(); switch (but = checkkey()) { case 'x': translate(tdir, 0.0, 0.0); break; case 'y': translate(0.0, tdir, 0.0); break; case 'z': translate(0.0, 0.0, tdir); break; case '-': tdir = -tdir; break; case '+': tdir = TRANS; break; case 27: /* ESC */ case 'q': vexit(); exit(0); default: ; } } vexit(); }
bool isBalanced(TreeNode *root) { int totaldepth; return getdepth(root, &totaldepth); }
bool isBalanced(TreeNode *root) { Result re; re = getdepth(root); return re.isbalanced; }