非递归实现交换二叉树的左右子节点
思路一:
两个队列
思路二:
栈
struct TreeNode
{
int m_nValue;
TreeNode *m_pLeft;
TreeNode *m_pRight;
};
void ExchangeNode(TreeNode *pRoot)
{
stack<TreeNode *> 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 BSTPrevIter_2(TreeNode *root)
{
stack<TreeNode *>nodeStack;
nodeStack.push(root);
while (!nodeStack.empty())
{
TreeNode *node = nodeStack.top();
nodeStack.pop();
if (node)
{
cout << node->num << " ";
}
if (node->right)
{
nodeStack.push(node->right);
}
if (node->left)
{
nodeStack.push(node->left);
}
}
cout << endl;
}
非递归中序遍历:入栈两次,第二次出栈时访问。第一次是作为子节点,在访问父节点的子节点时,将其入栈,第二次是作为父节点,将子节点入栈是,一并将其入栈,并放在两个子节点中间
void BSTInOrder(TreeNode *root)
{
stack<TreeNode *>nodeStack;
nodeStack.push(root);
TreeNode *curNode = NULL;
while (!nodeStack.empty())
{
curNode = nodeStack.top();
// 如果有左子树,要先处理: 如何标记已经被加了左子树的情况
// t表示子树情况
int t = 1;
while (!t)
{
if (curNode->left)
{
nodeStack.push(curNode->left);
t++;
}
else
{
nodeStack.pop();
t--;
cout << curNode->num << " ";
if (curNode->right)
{
nodeStack.push(curNode->right);
}
}
}
}
cout << endl;
}
void BSTInOrder_2(TreeNode *root)
{
stack<TreeNode *> nodes;
TreeNode *current = root;
// 如果nodes不为空,或者current不为NULL
while (!nodes.empty() || current)
{
if (current)
{
nodes.push(current);
current = current->left;
}
else
{
current = nodes.top();
nodes.pop();
cout << current->num << " ";
current = current->right;
}
}
}
非递归后序遍历:入栈两次,第二次出栈时访问。第一次是作为子节点,在访问父节点的子节点时,将其入栈,第二次是作为父节点,将子节点入栈是,一并将其入栈,并放在两个子节点之后
void BSTNextOrder(TreeNode *root)
{
stack<TreeNode *> nodes;
TreeNode *current = root;
TreeNode *parent = root;
nodes.push(root);
while (!nodes.empty())
{
// 是否要访问左子树
bool isFirst = true;
if (!current)
{
current = parent;
while (parent->num != nodes.top()->num)
{
cout << nodes.top()->num << " ";
nodes.pop();
}
cout << parent->num << " ";
nodes.pop();
parent = nodes.top();
nodes.pop();
isFirst = false;
}
// 对于parent,先将其左子树遍历完
if (current->left && isFirst)
{
parent = current;
nodes.push(current);
current = current->left;
}
if (current->right)
{
parent = current;
nodes.push(current);
current = current->right;
}
}
}
void BSTNextOrder_2(TreeNode *root)
{
stack<TreeNode *> sTravers, sVisit;
sTravers.push(root);
while (!sTravers.empty())
{
TreeNode *tmp = sTravers.top();
sTravers.pop();
sVisit.push(tmp);
if (tmp->left)
{
sTravers.push(tmp->left);
}
if (tmp->right)
{
sTravers.push(tmp->right);
}
}
while (!sVisit.empty())
{
cout << sVisit.top()->num << " ";
sVisit.pop();
}
}