求一棵二叉樹的高度,棵二叉樹

來源:互聯網
上載者:User

求一棵二叉樹的高度,棵二叉樹

利用遞迴來求一棵樹的高度,基本思想是:對於每一個非空節點,先求取其左子樹的高度,然後求取其右子樹的高度,最後取兩子樹中較高的一個加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;}

//結果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.