二叉树问题:递归方式实现二叉树先序、中序、后序遍历
问题描述:
用递归方式实现二叉树的先序、中序、后序遍历。
算法实现:
//二叉树节点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.找到递归抽象的规律,明确三种遍历方式节点打印节点的时机。
相关推荐
choupiaoyi 2020-05-27
baike 2020-05-09
steeven 2020-11-10
Tips 2020-10-14
nongfusanquan0 2020-08-18
yedaoxiaodi 2020-07-26
清溪算法君老号 2020-06-27
pengkingli 2020-06-25
yishujixiaoxiao 2020-06-25
清溪算法 2020-06-21
RememberMePlease 2020-06-17
nurvnurv 2020-06-05
SystemArchitect 2020-06-02
码墨 2020-05-29
清溪算法 2020-05-27
清溪算法 2020-05-25
bluewelkin 2020-05-19
dbhllnr 2020-05-15
steeven 2020-05-09