2021-10-29本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议

Java实现递归二叉树遍历 


 
 /**  java实现二叉树的遍历
 *  使用递归
 *  参考csdn文章
   *2021/10/29*/

import java.util.Scanner;
public class Node {
    /** 定义一个树以及它的左右孩子*/
 Node Left;
 Node Right;
 int data;

 Node(){}    //构造函数

/**使用递归构建树 */
 public Node Create(){
 Scanner in = new Scanner(System.in);
 int a = in.nextInt();
 if (a==-1){
 return null;
 }else{
 Node head = new Node();
 head.data = a;
 System.out.println(a+"的左子树");
 head.Left = Create();
 System.out.println(a+"的右孩子");
 head.Right = Create();
 return head;
 }
 }

 public void PrePrint(Node head){
 if (head!=null){
 System.out.println(head.data+" ");
 PrePrint(head.Left);
 PrePrint(head.Right);
 }
 }

 public void inorderPrePrint(Node head) {
 if (head != null) {
 inorderPrePrint(head.Left);
 System.out.println(head.data + "");
 inorderPrePrint(head.Right);
 }
 }

 public static void main(String[] args) {
 Node create = new Node();
 Node head;
 head=create.Create();
 head.PrePrint(head);
 System.out.println("\n");
 head.inorderPrePrint(head);
 }
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值