二叉树有三种遍历方式:前序、中序和后序。
递归遍历
1.前序遍历
public static void preTraversal(Node root)
{
if(root==null)
return ;
System.out.println(root.value);
preTraversal(root.left);
preTraversal(root.right);
}
2.中序遍历
public static void midTraversal(Node root)
{
if(root == null)
return ;
midTraversal(root.left);
System.out.println(root.value);
midTraversal(root.right);
}
3.后序遍历
public static void neTraversal(Node root)
{
if(root==null)
return;
neTraversal(root.left);
neTraversal(root.right);
System.out.println(root.value);
}
非递归方式实现
由于栈这种数据结构有“时光机”的性能,因此,利用栈进行非递归方式的遍历
1.前序遍历
public static void preOrder(Node root)
{
if(root==null)
return;
Stack<Node> stack = new Stack<Node>();
Node node = root;
stack.push(node);
while(!stack.isEmpty())
{
node = stack.pop();
System.out.println(node.value);//遍历根节点
if(node.right!=null)//如果左节点非空
stack.push(node.right);
if(node.left!=null)//右节点非空
stack.push(node.left);
}
}
2.中序遍历
public static void InO(Node root)
{
if (root == null)
return;
Stack<Node> stack = new Stack<>();
Node node = root;
while (node != null || !stack.isEmpty())
{
if (node != null)
{
stack.push(node);
node = node.left;
} else
{
node = stack.pop();
System.out.println(node.value);
node = node.right;
}
}
}
3.后序遍历
public static void houxubianli(Node root)
{
if (root == null)
return;
Stack<Node> s1 = new Stack<>();
Stack<Node> s2 = new Stack<>();
Node node = root;
s1.push(node);
while (!s1.isEmpty())
{
node = s1.pop();
s2.push(node);
if (node.right != null)
{
s1.push(node.right);
}
if (node.left != null)
{
s1.push(node.left);
}
}
while(!s2.isEmpty())
{
System.out.println(s2.pop());
}
}
栈s1用于储存子节点,s2储存根节点