1.题目
返回所有的叶子节点
2.程序
1 import java.util.List; 2 import java.util.Queue; 3 import java.util.LinkedList; 4 5 public class Leaf { 6 //定义树节点 7 public static class TreeNode{ 8 TreeNode left=null; 9 TreeNode right=null; 10 int value; 11 TreeNode(int value){ 12 this.value=value; 13 } 14 @Override 15 public String toString() { 16 return "<TreeNode value:"+ this.value+">"; 17 } 18 } 19 //遍历叶子节点 20 public List<TreeNode> getLeaf(TreeNode root){ 21 List<TreeNode> result=new LinkedList(); 22 Queue<TreeNode> nodeQueue=new LinkedList(); 23 TreeNode node=null; 24 nodeQueue.add(root); 25 while(!nodeQueue.isEmpty()){ 26 node=nodeQueue.poll(); 27 if(node.left==null){ 28 if(node.right==null){ 29 result.add(node); 30 }else{ 31 nodeQueue.add(node.right); 32 } 33 }else{ 34 nodeQueue.add(node.left); 35 if(node.right!=null){ 36 nodeQueue.add(node.right); 37 } 38 } 39 } 40 return result; 41 } 42 43 //主函数,用于测试 44 public static void main(String[] args){ 45 TreeNode root=new TreeNode(0); 46 root.left=new TreeNode(1); 47 root.right=new TreeNode(2); 48 root.left.left=new TreeNode(3); 49 root.left.right=new TreeNode(4); 50 root.right.left=new TreeNode(5); 51 root.right.right=new TreeNode(6); 52 Leaf leaf=new Leaf(); 53 System.out.println(leaf.getLeaf(root)); 54 } 55 }