后缀表达式构造二叉树

问题描述

通过后缀表达式构造其表达式树,每个操作符有一个或者两个操作数。

思路

先构建一个存放节点的栈。然后从左至右依次遍历postOrder。当节点为操作数时就将该节点压栈,当节点为操作符时就弹出该操作符的两个操作数作为其左右子节点。

代码

//辅助函数,用户判断字符是否为操作符
bool isOperator(char c)
{
	if (c == '+' || c == '-' || c == '*' || c == '/')
		return true;
	return false;
}

binaryTreeNode<char>* buildTreeByPostfix(const char* const thePostorder, const int theSize)
{
	if (theSize <= 0 || thePostorder == nullptr)
		return nullptr;

	std::stack<binaryTreeNode<char>*> theStack;
	for (int i = 0; i < theSize; i++)
	{	
		//如果当前节点为操作符号
		if (isOperator(thePostorder[i]))
		{
			binaryTreeNode<char>* theNode = new binaryTreeNode<char>(thePostorder[i]);
			theNode->right = theStack.top();
			theStack.pop();
            
            //一个操作符对应一个或者两个操作数
            //如果对应一个操作数,则该节点只有右节点,左节点为空
			if (theStack.empty())
			{
				theNode->left = nullptr;
			}
			else
			{
				theNode->left = theStack.top();
				theStack.pop();
			}
			
			theStack.push(theNode);
		}
		//当前节点为操作数
		else
			theStack.push(new binaryTreeNode<char>(thePostorder[i]));
	}
	return theStack.top();

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值