首先先來看一下樹的結構:
樹是n(n>=0)個有限個資料的元素集合,形狀像一顆倒過來的樹。
而二叉樹就是樹的一種特殊結構:
完全二叉樹的陣列表示
鍊錶儲存表示
下面我就實現一下二叉鏈的這種結構:
首先是它的節點的結構:
template struct binarytreenode
public:
binarytreenode* _left;//左子樹
binarytreenode* _right;//右子樹
t _data;//資料項
};
然後是它的基本成員函式:
template class binarytree
binarytree(const t* a, size_t size, const t& invalid)//有參建構函式
:_root(null)
binarytree(const binarytree& t)//拷貝構造
:_root(null)
binarytree& operator=(binarytreet)//賦值運算子的過載
return *this;
} ~binarytree()//析構函式 }
void prevorder()//前序遍歷
return cur;
} //複製二叉樹
node* _copy(node * root)
cur = new node(root->_data);//建立該節點
cur->_left = _copy(root->_left);
cur->_right = _copy(root->_right);
return cur;
} //刪除
void _delete(node * &root)
if (root->_left == null && root->_right == null)//該節點沒有左右孩子
_delete(root->_left);
_delete(root->_right);
} //前序遍歷:根節點--左子樹--右子樹
void _prevorder(node * root)
cout <_data>
_prevorder(root->_left);
_prevorder(root->_right);
} //中序遍歷:左子樹--根節點--右子樹
void _inorder(node * root)
_prevorder(root->_left);
cout <_data>
_prevorder(root->_right);
} //後序遍歷:左子樹--右子樹--根節點
void _postorder(node * root)
_prevorder(root->_left);
_prevorder(root->_right);
cout <_data>
} //層次遍歷
void _levelorder(node* root)
q.push(root);
while (!q.empty())
if (q.front()->_right != null)
cout <_data>
q.pop();
} }//節點個數
size_t _size(node * root)
return _size(root->_left) + _size(root->_right) + 1;//當左子樹或者右子樹不為空時,該節點有資料
} //二叉樹的深度
size_t _depth(node * root)
size_t leftdepth = _depth(root->_left);
size_t rightdepth = _depth(root->_right);
/*if (leftdepth >= rightdepth)
else
return rightdepth + 1;*/
return leftdepth > rightdepth?leftdepth + 1 : rightdepth+1;
} //葉子節點個數
size_t _leafsize(node * root)
if (root->_left == null&&root->_right == null)
return _leafsize(root->_left)+_leafsize(root->_right);
}private:
node * _root;//根節點
};
測試用例以及結果如下:
本文出自 「不斷進步的空間」 部落格,請務必保留此出處
遞迴實現二叉樹
二叉樹是一種非線性結構,用途廣泛。二叉樹的每個結點的度都不大於2,所以一般用二叉鍊錶來實現二叉樹。二叉樹可以分為根結點,左子樹和右子樹,左子樹 右子樹依然這麼劃分,所以用遞迴實現二叉樹的邏輯是比較簡單的,只需不斷對子樹進行劃分即可。include include include using name...
二叉樹遍歷遞迴實現
include include define flag int define l 0 define r 1 typedef struct tree tree tree init tree int data void destroy tree tree root void insert tree t,...
遍歷二叉樹 遞迴實現
二叉樹作為樹的一種,是一種重要的資料結構,也是面試官經常考的東西。二叉樹中的面試題比較常見的題型大概有下面幾個 建立一顆二叉樹 先序,中序,後序 遍歷一顆二叉樹 先序,中序,後序和層次遍歷 求二叉樹中葉子節點的個數 求二叉樹的高度等等。binarytree.h pragma once templat...