二叉树的遍历及相关知识


1. 递归遍历

1.1 前序遍历

vector<int> res;
vector<int> PreTravelsal(vector<int> res, TreeNode* root)
{
	res.clear();
	travelsal(root);
	return res;	
}
void travelsal(TreeNode* cur)
{
	if(cur == NULL) return;
	res.push_back(cur->val);
	travelsal(cur->left);
	travelsal(cur->right);
}

1.2 中序遍历

vector<int> res;
vector<int> PreTravelsal(vector<int> res, TreeNode* root)
{
	res.clear();
	travelsal(root);
	return res;	
}
void travelsal(TreeNode* cur)
{
	if(cur == NULL) return;
	res.push_back(cur->val);
	//travelsal(cur->left);
	res.push_back(cur->val);
	travelsal(cur->right);
}

1.3 后序遍历

vector<int> res;
vector<int> PreTravelsal(vector<int> res, TreeNode* root)
{
	res.clear();
	travelsal(root);
	return res;	
}
void travelsal(TreeNode* cur)
{
	if(cur == NULL) return;
	//res.push_back(cur->val);
	travelsal(cur->left);
	travelsal(cur->right);
	res.push_back(cur->val);
}

2. 迭代遍历

2.1 前序遍历

vector<int> travelsal(TreeNode* root)
{
	vector<int> res;
	stack<TreeNode*> st;
	if(root == NULL) return res;
	st.push(root);
	while(!st.empty())
	{
		TreeNode* cur = st.top();
		st.pop();
		res.push_back(cur->val);
		if(cur->right) st.push(cur->right);
		if(cur->left) st.push(cur->left);
	}
	return res;
}

2.2 后序遍历

vector<int> travelsal(TreeNode* root)
{
	vector<int> res;
	stack<TreeNode*> st;
	if(root == NULL) return res;
	st.push(root);
	while(!st.empty())
	{
		TreeNode* cur = st.top();
		st.pop();
		res.push_back(cur->val);
		if(cur->left) st.push(cur->left);
		if(cur->right) st.push(cur->right);
	}
	reverse(res.begin(), res.end());
	return res;
}

2.3 中序遍历

vector<int> travelsal(TreeNode* root)
{
	vector<int> res;
	stack<TreeNode*> st;
	TreeNode* cur = root;
	while(cur != NULL || !st.empty())
	{
		if(cur != NULL)
		{
			st.push(cur);
			cur = cur->left;
		}
		else
		{
			cur = st.top();
			st.pop();
			res.push_back(cur->val);
			cur = cur->right;
		}
	}
	return res;

3. 层序遍历

vector<int> travelsal(TreeNode* root)
{
	vector<int> res;
	queue<TreeNode*> que;
	if(root == NULL) return res;
	que.push(root);
	while(!que.empty())
	{
		int n = que.size();
		for(int i = 0; i < n; i++)
		{
			TreeNode* cur = que.front();
			que.pop();
			res.push_back(cur->val);
			if(cur->left) que.push(cur->left);
			if(cur->right) que.push(cur->right);
		}
	}
	return res;
}

4. 二叉树的种类

  1. 完全二叉树:一根二叉树只有度为0的结点和度为2的结点,并且度为0的结点在同一层上,其深度为k,结点数为2^k-1;在这里插入图片描述
  2. 完全二叉树:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^(h-1) 个节点。
    在这里插入图片描述
  3. 二叉搜索树:若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉排序树。
    在这里插入图片描述
    4.平衡二叉搜索树:又被称为AVL(Adelson-Velsky and Landis)树,且具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值