java 二叉树 递归算法_二叉树的递归实现(java)

本文介绍了如何使用Java递归算法构造一个3层二叉树。首先创建根节点,然后根据左右子节点是否为空来决定递归构造。通过控制层数来迭代构建树的结构,并提供了相应的代码示例进行详细解释。
摘要由CSDN通过智能技术生成

这里演示的二叉树为3层。

递归实现,先构造出一个root节点,先判断左子节点是否为空,为空则构造左子节点,否则进入下一步判断右子节点是否为空,为空则构造右子节点。

利用层数控制迭代次数。

依次递归第二段的内容。

下面是代码,很简单,耐心看看就懂了。

package Construct;

public class ConstructTree {

private int count = 0;

class Node {

int i;

Node left;

Node right;

public Node(int i) {

this.i = i;

}

}

public static void main(String[] args) throws Exception {

ConstructTree ct = new ConstructTree();

ct.startRun(3);

}

public void startRun(int n) {

Node root = new Node(count++);

System.out.println(count - 1+" root "+n);

Node current = root;

Construct(current,n - 1);

}

public void Construct(Node current, int n) {

if(n > 0) {

if(current.left == null) {

current.left = new Node(count++);

System.out.println(count - 1+" left "+n);

Construct(current.left, n - 1);

}

if(current.right == null) {

current.right = new Node(count++);

System.out.println(count - 1+" right "+n);

Construct(current.right, n - 1);

}

}

}

}

输出:(下面输出对应值)节点的数据  左节点/右节点  层数

0 root 3

1 left 2

2 left 1

3 right 1

4 right 2

5 left 1

6 right 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值