首页 > 学院 > 开发设计 > 正文

二叉树的递归实现(java)

2019-11-14 15:04:12
字体:
来源:转载
供稿:网友

  这里演示的二叉树为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  31 left 22 left 13 right  14 right  25 left 16 right  1

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表