求一棵二叉樹的高度,棵二叉樹
利用遞迴來求一棵樹的高度,基本思想是:對於每一個非空節點,先求取其左子樹的高度,然後求取其右子樹的高度,最後取兩子樹中較高的一個加1作為以該節點為根的樹的高度;對於空節點,直接返回0就可以了。求整棵樹的高度只需將此思想運用到根節點上即可。
struct BST_Node{ int m_value; BST_Node* left_child; BST_Node* rigth_child;};class BSTree{private: int nodeCount; BST_Node* root; ...//省略建樹及其他動作的方法 int _GetHeight(BST_Node* node) { if(node == NULL) return 0; int leftHeight = _GetHeight(node->left_child); int rightHeight = _GetHeight(node->rigth_child); int GreaterHeight = leftHeight > rightHeight ? leftHeight : rightHeight; return 1 + GreaterHeight; }public: BSTree() :nodeCount(0),root(NULL) { } ...//省略解構函式及其他動作樹的方法 int GetHeight() { return _GetHeight(root); }};//測試代碼int _tmain(int argc, _TCHAR* argv[]){ int myarray[] = {10,6,15,4,8,1,17,14,5,13,7,11,9,12,16}; BSTree tree; ...//省略建樹及先序遍曆樹的語句 int height = tree.GetHeight(); cout<<height<<endl; return 0;}
//結果