Cracking the coding interview--Q4.4

题目

原文:

Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists).

译文:

给一个二叉查找树,设计一个算法将每一层的所有结点构建为一个链表(例如:如果树深度为D,你将要构建D个链表)

解答

此题本质是BFS ,也就是说,如果已经构建了第i层结点的链表, 那么将此链表中每个结点的左右孩子结点取出,即可构建第i+1层结点的链表。代码如下:

import java.util.*;

class Q4_4{

	public static LinkedList<LinkedList<TreeNode>> buildLevelList(TreeNode head){
		LinkedList<LinkedList<TreeNode>> result=new LinkedList<LinkedList<TreeNode>>();
		LinkedList<TreeNode> ls=new LinkedList<TreeNode>();
		ls.add(head);
		result.add(ls);
		int level=0;
		while(result.get(level).size()>0){
			LinkedList<TreeNode> l=result.get(level);
			Iterator<TreeNode> iterator=l.iterator();
			LinkedList<TreeNode> ll=new LinkedList<TreeNode>();
			while(iterator.hasNext()){
				TreeNode tnode=iterator.next();
				if(tnode.lchild!=null){
					ll.add(tnode.lchild);
				}
				if(tnode.rchild!=null){
					ll.add(tnode.rchild);
				}
			}
			result.add(ll);
			level++;
		}
		return result;
	}
	public static void main(String[] args){
		int[] arr = new int[]{6,7,1,2,5,8,9,3,4};
		TreeNode root = TreeNode.createBinaryTree(arr);
		LinkedList<LinkedList<TreeNode>>  t = buildLevelList(root);
		for(LinkedList<TreeNode> outEntry:t){
			for(TreeNode tnode:outEntry){
				System.out.print(tnode.value+" ");
			}
			System.out.println();
		}
	}
}

class TreeNode{
	int value;
	TreeNode lchild;
	TreeNode rchild;
	TreeNode parent;
	
	public static void insert(TreeNode tnode,int x,TreeNode p){
		if(tnode==null){
			tnode=new TreeNode();
			tnode.value=x;
			tnode.lchild=null;
			tnode.rchild=null;
			if(p.value>x)
				p.lchild=tnode;
			else
				p.rchild=tnode;
			tnode.parent=p;
			return;
		}
		
		if(x<tnode.value){
			insert(tnode.lchild,x,tnode);
		}else{
			insert(tnode.rchild,x,tnode);
		}
	}
	
	public static TreeNode createBinaryTree(int[] values){
		TreeNode root=new TreeNode();
		root.value=values[0];
		for(int i=1;i<values.length;i++){
			insert(root,values[i],root);
		}
		return root;
	}
}

如有更好方法,还望交流!

---EOF---


你可能感兴趣的:(Cracking the coding interview--Q4.4)