您的位置:首页 > 编程语言 > Java开发

二叉树的递归实现(java)

2015-11-16 18:23 429 查看
  这里演示的二叉树为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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: