ListNode实现
class ListNode<V>{
V value;
ListNode next;
public ListNode(V value){
this.value=value;
}
@Override
public String toString(){
ListNode p=next;
StringBuilder sb=new StringBuilder("["+value+"");
while(p!=null){
sb.append(p.value+(p.next==null?"":","));
p=p.next;
}
sb.append("]");
return sb.toString();
}
}
TreeNode
class TreeNode<V>{
V value;
TreeNode left=null;
TreeNode right=null;
public TreeNode(V value){
this.value=value;
}
}
NodeAndHeight
为便于知道节点层次,需要一个既有树节点又有层次的方法
class NodeAndHeight{
TreeNode<Integer>node;
int height;
public NodeAndHeight(TreeNode<Integer>node,int height){
this.node=node;
this.height=height;
}
}
主方法
public class Main{
public ListNode getTreeLevel(TreeNode root,int height){
if(root!=null&&height==1)return new ListNode(root.value);//根高度为1只有一层
if(root==null)return null;//根为空
ListNode head=null;
ListNode last=null;
Queue<NodeAndHeight>queue=new LinkedList();//队列
queue.offer(new NodeAndHeight(root,1));//头节点入队
while(queue!=null){//队列不为空
NodeAndHeight poll=queue.poll();//弹出队
//满足要求的层次加入链表中
if(poll.height==height){
if(head==null){//头节点为空
head=new ListNode(root.value);
last=head;
}else{
last.next=new ListNode(root.value);
last=last.next;
}
}else if(poll.height>height){
break;
}
if(poll.left!=null&&poll.height<height){//左子入队
queue.offer(new NodeAndHeight(poll.left,1+poll.height));
}
if(poll.right!=null&&poll.height<height){//右子入队
queue.offer(new NodeAndHeight(poll.right,1+poll.height));
}
}
return head;
}
//测试
public static void main(String[] args) {
TreeNode node=new TreeNode(1);
TreeNode node2=new TreeNode(2);
TreeNode node3=new TreeNode(3);
TreeNode node4=new TreeNode(4);
TreeNode node5=new TreeNode(5);
node.left=node2;
node.right=node3;
node2.left=node4;
node3.right=node5;
ListNode list=new Main().getTreeLevel(node, 3);//打印输出第三层所有节点
System.out.println(list);
}
}

3238

被折叠的 条评论
为什么被折叠?



