二叉树的递归实现(java)

时间:2023-03-09 04:34:27
二叉树的递归实现(java)

  这里演示的二叉树为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