/** * 前序遍历 * 递归 */
public void preOrder(BinaryNode Node){
if (Node != null)
{
System.out.print(Node.element + " ");
preOrder(Node.left);
preOrder(Node.right);
}
}
/**
* 前序遍历
* 非递归
*/
public void preOrder1(BinaryNode<AnyType> Node)
{
Stack<BinaryNode> stack = new Stack<>();
while(Node != null || !stack.empty())
{
while(Node != null)
{
System.out.print(Node.element + " ");
stack.push(Node);
Node = Node.left;
}
if(!stack.empty())
{
Node = stack.pop();
Node = Node.right;
}
}
}
/**
* 中序遍历
* 非递归
*/
public void midOrder1(BinaryNode<AnyType> Node)
{
Stack<BinaryNode> stack = new Stack<>();
while(Node != null || !stack.empty())
{
while (Node != null)
{
stack.push(Node);
Node = Node.left;
}
if(!stack.empty())
{
Node = stack.pop();
System.out.print(Node.element + " ");
Node = Node.right;
}
}
}
后续遍历非递归
public static void postOrder_Stack(Node root){//后续遍历
Stack<Node> stack = new Stack<Node>();
Stack<Node> output = new Stack<Node>();//构造一个中间栈来存储逆后续遍历的结果
while(node != null || !stack.empty()){
if(node != null){
output.push(node);
stack.push(node);
node = node.right;
}else{
node = stack.pop();
node = node.left;
}
}
while(output.size()>0){
printNode(output.pop());
}
}
二叉树层次遍历
基于java实现二叉树层次遍历的思想,要借助数据结构队列的先进先出的功能,先将根节点入队,在队不为空的条件下while循环,当前节点是队头节点,将其出队并访问,如果当前节点的左节点不为空将左节点入队,如果当前节点的右节点不为空将其入队。这样保证了出队顺序也是从左到右依次出队。
代码实现如下:
import java.util.LinkedList;
public class LevelOrder
{
public void levelIterator(BiTree root)
{
if(root == null)
{
return ;
}
LinkedList<BiTree> queue = new LinkedList<BiTree>();
BiTree current = null;
queue.offer(root);//将根节点入队
while(!queue.isEmpty())
{
current = queue.poll();//出队队头元素并访问
System.out.print(current.val +"-->");
if(current.left != null)//如果当前节点的左节点不为空入队
{
queue.offer(current.left);
}
if(current.right != null)//如果当前节点的右节点不为空,把右节点入队
{
queue.offer(current.right);
}
}
}
}
网友评论