二叉树的算法

前中后层序遍历的迭代和递归实现

前:中间节点最先处理;

中:中间节点在中间处理;

后:中间节点在最后处理;

void preOrder(node* root, vector<int>& p_vec)
{
	stack<node*> p_sta;

	if(root) p_sta.push(root);
	while (!p_sta.empty())
	{
		//从栈中获取元素放入数组,然后出栈
		node* cur = p_sta.top();
		p_vec.push_back(cur->data);
		p_sta.pop();
		if (cur->right) p_sta.push(cur->right);
		if (cur->left) p_sta.push(cur->left);
	}
}
void inOrder(node* root, vector<int>& vec)
{
	stack<node*> in_sta;
	node* cur = root;

	while (cur != nullptr || !in_sta.empty())
	{
		//一直循环找到以一个结点开始的最左结点
		while (cur != nullptr)
		{
			in_sta.push(cur);
			cur = cur->left;
		}
		//找到了
		node* leftNode = in_sta.top();
		in_sta.pop();
		vec.push_back(leftNode->data);
		//因为中序遍历,遍历完最左结点,就应该是这个结点的右节点了
		cur = leftNode->right;
	}
}
void postOrder(node* root,vector<int>& p_vec)
{
	stack<node*> p_sta;

	if(root) p_sta.push(root);
	while (!p_sta.empty())
	{
		//从栈中获取元素放入数组,然后出栈
		node* cur = p_sta.top();
		p_vec.push_back(cur->data);
		p_sta.pop();
		if (cur->left) p_sta.push(cur->left);
		if (cur->right) p_sta.push(cur->right);
	}
	reverse(p_vec.begin(),p_vec.end());
}

void levelOrder(node* root, vector<int>& vec)
{
	if (root == nullptr) return;
	queue<node*> que;
	que.push(root);
	node* cur = nullptr;

	while (!que.empty())
	{
		cur = que.front();
		vec.push_back(cur->data);
		que.pop();

		if (cur->left)  que.push(cur->left);
		if (cur->right) que.push(cur->right);
	}
}

void levelOrder1(node* root, vector<vector<int>>& vec)
{
	if (root == nullptr) return;
	queue<node*> que;
	que.push(root);
	node* curr = nullptr;
	int j = 0;

	while (!que.empty())
	{
		int len = que.size();
		vector<int> svec;
		for (int i = 0; i < len; ++i)
		{
			curr = que.front();
			svec.push_back(curr->data);
			que.pop();

			if (curr->left)  que.push(curr->left);
			if (curr->right) que.push(curr->right);
		}
		j++;
		vec.push_back(svec);
	}
}

前中或者后中得其一的实现---链接

路径总和1---链接

路径总和2

对称二叉树-----左起遍历和右起遍历比较---101

相同树-----都左旗或者右起遍历比较---100

反转二叉树-----从根节点开始,左右子节点交换即可

二叉树的最近公共祖先-----236

先递进入最下层,从最下层开始往上找;

找到的条件:1,在当前节点的左右子树存在两个节点;2,当前节点就是其中一个节点,而且子树存在另一个节点
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值