非递归实现交换二叉树的左右子节点

思路一:

         两个队列

思路二:

         栈

struct TreeNode
{
	int m_nValue;
	TreeNode *m_pLeft;
	TreeNode *m_pRight;
};

void ExchangeNode(TreeNode *pRoot)
{
	stack s;
	if (pRoot)
		s.push(pRoot);
	while (!s.empty())
	{
		TreeNode *cur = s.top();
		s.pop();
		TreeNode *pTmp = cur->m_pLeft;
		cur->m_pLeft = cur->m_pRight;
		cur->m_pRight = pTmp;
		if (cur->m_pLeft)
			s.push(cur->m_pLeft);
		if (cur->m_pRight)
			s.push(cur->m_pRight)
	}
}


非递归前序、中序、后序遍历

两个栈

void PreOrderNonRecursive(TreeNode * node) 
{
	stack s;
	s.push(node);
	while(!s.empty()) 
	{
		TreeNode * n = s.pop();
		visit(n);
		if(n->right!=NULL) s.push(n->right);
		if(n->left!=NULL) s.push(n->left);
	}
}

void InOrderNonRecursive(TreeNode * node) 
{
	stack s;
	TreeNode *current = node;
	while (!s.empty() || current != NULL)
	{
		if (current != NULL)
		{
			s.push(current);
			current = current->left;
		}
		else
		{
			current = s.pop();
			visit(current);
			current = current->right;
		}
	}
}

void PostOrderNonRecursive(TreeNode * node) 
{
	stack sTraverse, sVisit;
	sTraverse.push(node);
	while (!sTraverse.empty())
	{
		TreeNode *p = sTraverse.pop();
		sVisit.push(p);
		if (p->left != NULL)
		{
			sTraverse.push(p->left);
		}
		if (p->right != NULL)
		{
			sTraverse.push(p->right);
		}
	}
	while (!sVisit.empty())
	{
		visit(sVisit.pop());
	}
}


void InOrderTree(TreeNode *root)
{
	stack s;	
	TreeNode *pNode = root;

	while (!s.empty() || pNode)
	{			
		while (pNode)
		{
			s.push(pNode);
			pNode = pNode->left;
		}
		if (!s.empty())
		{
			pNode = s.top();
			s.pop();
			cout << pNode->val << endl;
			pNode = pNode->right;			
		}
	}
}

void PostOrderTree(TreeNode *root)
{
	stack s;
	s.push(root);
	TreeNode *cur = root;
	TreeNode *pre = NULL;
	while (!s.empty())
	{
		cur = s.top();
		if ((cur->left == NULL && cur->right == NULL) || 
			(pre != NULL && (pre == cur->left || pre == cur->right)))
		{
			cout << cur->val << endl;
			s.pop();
			pre = cur;
		}
		else
		{
			if (cur->right)
			{
				s.push(cur->right);
			}
			if (cur->left)
			{
				s.push(cur->left);
			}
		}
	}
}


你可能感兴趣的:(算法)