sunjunior 2020-04-08
问题描述:
用递归方式实现二叉树的先序、中序、后序遍历。
算法实现:
//二叉树节点private class Node { public int value; public Node left; public Node right; public Node(int value) { this.value = value; }}//前序遍历public void preOrderRecur(Node head) { if (head == null) { return; } System.out.println("output value = " + head.value); preOrderRecur(head.left); preOrderRecur(head.right);}//中序遍历public void inOrderRecur(Node head) { if(head == null) { return; } inOrderRecur(head.left); System.out.println("output value = " + head.value); inOrderRecur(head.right);}//后序遍历public void postOrderRecur(Node head) { if(head == null) { return; } postOrderRecur(head.left); postOrderRecur(head.right); System.out.println("output value = " + head.value);}
算法解析:
1.首先要从数据结构的角度,理解二叉树的先序、中序、后序遍历的遍历方式;
2.使用递归方式,要明确终止条件;
3.找到递归抽象的规律,明确三种遍历方式节点打印节点的时机。