int main(int argc, const char * argv[]) { AVLTree b= create_tree(); Insert(&b, 20, "jordan"); Insert(&b, 42, "james"); Delete(&b, 20); Insert(&b, 32, "jack"); Insert(&b, 50, (void*)9); Insert(&b, 6, (void*)12); Insert(&b, 7, (void*)'j'); Insert(&b, 4, (void*)'x'); Insert(&b, 1, (void*)'v'); Insert(&b, 100, "abby"); Insert(&b, 90, "gabby"); Insert(&b, 80, "grace"); Insert(&b, 70, "david"); Insert(&b, 39, "Chris"); printf("pre-order\n"); PrintPreOrder(&b); printf("in-order\n"); PrintInOrder(&b); printf("post-order\n"); PrintPostOrder(&b); printf("Distance from root %d\n",DistanceFromRoot(&b, 70)); printf("tree height %d\n",TreeHeight(&b)); printf("item: %s\n",Find(&b, 42)); Delete(&b, 42); printf("item: %s\n",Find(&b, 39)); printf("tree height %d\n",TreeHeight(&b)); return 0; }
int TreeHeight( pNode root ) { if( root == NULL ) { return 0; } else { int lh = TreeHeight( root->Left ); int rh = TreeHeight( root->Right ); return 1 + ((lh > rh) ? lh : rh); } }
int TreeHeight(const TreeNode *root,bool & balanced) { const int LHeight=root->leftchild ? TreeHeight(root->leftchild,balanced)+1:0; if(!balanced) { return 0; } const int RHeight=root->rightchild ? TreeHeight(root->rightchild,balanced)+1:0; if (!balanced) return 0; const int diff=LHeight-RHeight; if(diff<-1 || diff>1) balanced=false;//在这里完成对应的balanced 判断,然后通过直接返回0来进行判断 return (LHeight>RHeight ? LHeight:RHeight); }
bool IsBalancedTree(const TreeNode *root) { bool balanced = true; if(root) { TreeHeight(root,balanced); } return balanced; }
void LevelOrderTraversal(TreeNode * root) { if(root) { int Height = TreeHeight(root); for (int Level=1; Level <=Height; Level++) { LevelNodes (root,Level); std::cout << " \n" << std::endl; } } }
int BTree::Height() { int x=TreeHeight(root); return x; }
int TreeHeight(TreeNode *&root) { if(!root) return 0; return MAX(TreeHeight(root->Left),TreeHeight(root->Right))+1; }