对二叉树进行层序遍历
二叉树定义
lass TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
使用队列进行层序遍历
public static void traverse_level(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
if(root!=null) queue.offer(root) ;
while (!queue.isEmpty()){
root = queue.poll();
System.out.println(root.val);
if(root.left!=null){
queue.offer(root.left);
}
if(root.right!=null){
queue.offer(root.right);
}} }
测试
public static void main(String[] args) {
TreeNode root1 = new TreeNode(3);
root1.left=new TreeNode(9);
root1.right=new TreeNode(20);
root1.right.left= new TreeNode(15);
root1.right.right= new TreeNode(7);
traverse_level(root1);
}
结果
3-9-20-15-7
|