一、基本概念
每个结点最多有两棵子树,左子树和右子树,次序不可以颠倒。
性质:
1、非空二叉树的第n层上至多有2^(n-1)个元素。
2、深度为h的二叉树至多有2^h-1个结点。
满二叉树:所有终端都在同一层次,且非终端结点的度数为2。
在满二叉树中若其深度为h,则其所包含的结点数必为2^h-1。
完全二叉树:除了最大的层次即成为一颗满二叉树且层次最大那层所有的结点均向左靠齐,即集中在左面的位置上,不能有空位置。
对于完全二叉树,设一个结点为i则其父节点为i/2,2i为左子节点,2i+1为右子节点。
二、二叉树的遍历
遍历即将树的所有结点访问且仅访问一次。按照根节点位置的不同分为前序遍历,中序遍历,后序遍历。
前序遍历:根左右
中序遍历:左跟右
后序遍历:左右根
(规律:就是访问根节点的顺序。)
例如:求下面树的三种遍历
前序遍历:abdecfg
中序遍历:dbeafcg
后序遍历:debfgca
三、遍历的实现
#include <iostream>
#include <stack>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode * m_pLeft;
BinaryTreeNode * m_pRight;
};
//构建二叉树
BinaryTreeNode * createTree()
{
int value;
cin >> value;
if (value == -1)
return NULL;
BinaryTreeNode * temp = new BinaryTreeNode();
temp->m_nValue = value;
temp->m_pLeft = createTree();
temp->m_pRight = createTree();
return temp;
}
//递归实现前序遍历
void qianxubl(BinaryTreeNode * root)
{
if (root == NULL)
return;
else
{
cout << root->m_nValue << " ";
qianxubl(root->m_pLeft);
qianxubl(root->m_pRight);
}
}
//非递归实现前序遍历
void xunhuanqianxubianli(BinaryTreeNode * root)
{
stack<BinaryTreeNode *> ss;
BinaryTreeNode * temp = root;
if (root == NULL)
{
return;
}
while (temp || ss.size() > 0)
{
while (temp)
{
cout << temp->m_nValue << " ";
ss.push(temp);
temp = temp->m_pLeft;
}
temp = ss.top();
ss.pop();
temp = temp->m_pRight;
}
}
//非递归实现后续遍历
void xunhuanzhongxubianli(BinaryTreeNode * root)
{
stack<BinaryTreeNode*> ss;
if (root == NULL)
{
return;
}
BinaryTreeNode * pRoot = root;
while (pRoot || ss.size() > 0)
{
while (pRoot)
{
ss.push(pRoot);
pRoot = pRoot->m_pLeft;
}
BinaryTreeNode * temp = ss.top();
ss.pop();
cout << temp->m_nValue << " ";
pRoot = temp->m_pRight;
}
}
//咳咳,非递归实现后续遍历暂时没写
int main()
{
BinaryTreeNode * root = createTree();
//qianxubl(root);
//xunhuanqianxubianli(root);
xunhuanzhongxubianli(root);
return 0;
}