分层打印二叉树

问题:

把一个二叉树,安装从root到leaf的顺序把每一层上的node从左到右打印出来。

分析:
利用两个arraylist,一个arraylist装上一层的node, 另一个arraylist装上一层的child。如果上一层arraylist空了,两个arraylist互换。

代码:

//print the binary tree by level
public static void printByLevel(Node node) {
	ArrayList<Node> list1 = new ArrayList<Node>();
	ArrayList<Node> list2 = new ArrayList<Node>();
	
	list1.add(node);
	
	while(list1.size() != 0) {
		for (int i = 0; i < list1.size(); i++) {
			System.out.print(list1.get(i).value + " ");
			if (list1.get(i).leftChild != null) list2.add(list1.get(i).leftChild);
			if (list1.get(i).rightChild != null) list2.add(list1.get(i).rightChild);
		} 
		System.out.println();
		list1.clear();
		
		ArrayList<Node> temp = list1;
		list1 = list2;
		list2 = temp;
	}
}

class Node {
    Node leftChild = null;
    Node rightChild = null;
    String name;

    Node(String name) {
        this.name = name;
    }
}

转载请注明出处:http://blog.csdn.net/beiyeqingteng/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
分层二叉树是一种特殊的二叉树,每层节点数都是2的幂次方。以下是用Java实现分层二叉树的代码: ```java class Node { int val; Node left, right; public Node(int val) { this.val = val; this.left = null; this.right = null; } } class LayeredBinaryTree { Node root; public LayeredBinaryTree() { root = null; } public void insert(int val) { if (root == null) { root = new Node(val); return; } Node curr = root; while (curr.left != null && curr.right != null) { if (val <= curr.val) { curr = curr.left; } else { curr = curr.right; } } if (val <= curr.val) { curr.left = new Node(val); } else { curr.right = new Node(val); } } public void printLevelOrder() { int h = height(root); for (int i = 1; i <= h; i++) { printLevel(root, i); System.out.println(); } } public int height(Node node) { if (node == null) { return 0; } else { int lheight = height(node.left); int rheight = height(node.right); return Math.max(lheight, rheight) + 1; } } public void printLevel(Node node, int level) { if (node == null) { return; } if (level == 1) { System.out.print(node.val + " "); } else if (level > 1) { printLevel(node.left, level - 1); printLevel(node.right, level - 1); } } } ``` 这里定义了一个Node类和LayeredBinaryTree类,Node类表示树中的节点,LayeredBinaryTree类表示分层二叉树。insert方法用于插入节点,printLevelOrder方法用于按层遍历并打印分层二叉树,height方法用于计算分层二叉树的高度,printLevel方法用于打印某一层的节点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值