二叉树的遍历如果使用递归调用基本没什么问题,这里主要是讲如何使用非递归方法实现二叉树的遍历。
由于递归调用程序实际上使用了栈来保存方法中的变量值,在非递归遍历的方法中我们需要基于栈的方法。先来看看这个方法
/// <summary>
/// 非递归中序遍历二叉树
/// </summary>
/// <param name="root"></param>
static void InOrderTraverse(BinaryTreeNode root)
{
BinaryTreeNode temp = root;
Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
stack.Push(root);
while (stack.Count > 0)
{
while (temp != null)
{
temp = temp.left;
stack.Push(temp);
}
stack.Pop();
//如果为0证明这时右边节点为null
if (stack.Count > 0)
{
temp = stack.Pop();
Console.WriteLine(temp.data);
temp = temp.right;
stack.Push(temp);
}
}
}
节点temp在这里是起一个标识的作用 ...