树的遍历
Posted aiguozou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了树的遍历相关的知识,希望对你有一定的参考价值。
- 前序遍历:中左右
- 中序编列:左中右
- 后续编列:左右中
//前序遍历
public static void preOrder(Node node)
if (node == null)
return;
System.out.print(node.value);
preOrder(node.left);
preOrder(node.right);
//中序遍历
public static void inOrder(Node node)
if (node == null)
return;
inOrder(node.left);
System.out.print(node.value);
inOrder(node.right);
//后序遍历
public static void postOrder(Node node)
if (node == null)
return;
postOrder(node.left);
postOrder(node.right);
System.out.print(node.value);
/**
* 非递归实现
*/
//前序遍历
public static void preOrder02(Node node)
Stack<Node> stack = new Stack<>();
while (node != null || !stack.isEmpty())
while (node != null)
System.out.print(node.value);
stack.push(node);
node = node.left;
node = stack.pop().right;
//中序遍历
public static void inOrder02(Node node)
Stack<Node> stack = new Stack<>();
while (node != null || !stack.isEmpty())
while (node != null)
stack.push(node);
node = node.left;
node = stack.pop();
System.out.print(node.value);
node = node.right;
//后序遍历
public static void postOrder2(Node node)
Stack<Node> stack = new Stack<Node>();
Stack<Integer> tag = new Stack<Integer>();
while (node != null || !stack.isEmpty())
if (node != null)
stack.push(node);
tag.push(1); //第一次访问
node = node.left;
else
if (tag.peek() == 2)
System.out.print(stack.pop().value);
tag.pop();
else
tag.pop();
tag.push(2); //第二次访问
node = stack.peek().right;
测试用例
//测试用例
public static void test(Node node)
System.out.print("递归_前序排序:");
preOrder(node);
System.out.println();
System.out.print("前序排序:");
preOrder02(node);
System.out.println();
System.out.print("递归_中序遍历:");
inOrder(node);
System.out.println();
System.out.print("中序遍历:");
inOrder02(node);
System.out.println();
System.out.print("递归_后序排序:");
postOrder(node);
System.out.println();
System.out.print("后序排序:");
postOrder2(node);
System.out.println();
public static void main(String[] args)
BST<Integer, Integer> bst = new BST<>();
bst.put(3, 3);
bst.put(2, 2);
bst.put(4, 4);
TreeOrder.test(bst.root);
输出
递归_前序排序:324
前序排序:324
递归_中序遍历:234
中序遍历:234
递归_后序排序:243
后序排序:243
以上是关于树的遍历的主要内容,如果未能解决你的问题,请参考以下文章