二叉树打印-相同层值打印

 

题目:二叉树如下{1,2,3,4,5,6,null,7}
   1
  2 3
  4 5 6
 7

要求结果打印: 1,2 3 ,4 5 6 ,7,

 

 思路:一般二叉树遍历,从上往下打印二叉树每个节点,相同层从左往右打印因为这道题目是要按层次打印,所以就要确定当前层的最右节点是哪个,
当前层的最右节点是需要根据上层确认,这样的话用两个变量保存上一层和当前层最右节点看看能不能解决?

public static void printTreeAll(TreeNode root){
        Queue<TreeNode> queue = new LinkedList<>();//二叉树遍历常用队列解决
        queue.offer(root);//根节点直接加入队列
        TreeNode lastNode = root;//当前层最右侧节点,初始赋值根节点
        TreeNode nextNode = null;//下一行节点
        TreeNode currentNode;//打印当前节点信息
        while(!queue.isEmpty()){
            currentNode = queue.poll();
            System.out.print(currentNode.val+" ");
            if(currentNode.left != null){
                queue.offer(currentNode.left);
                nextNode = currentNode.left;//先将左节点赋值最右,如果存在右节点,右节点再次赋值

            }
            if(currentNode.right != null){
                queue.offer(currentNode.right);
                nextNode = currentNode.right;//右节点再次赋值,保证nextNode是最右节点
            }
            if(currentNode == lastNode){//判断当前节点是不是最右节点
                System.out.print(",");
                lastNode = nextNode;//lastNode更新,进行下一次循环
            }
        }

    }

测试代码:

 public static void main(String[] args) {
        TreeNode t1 = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        TreeNode t3 = new TreeNode(3);
        TreeNode t4 = new TreeNode(4);
        TreeNode t5 = new TreeNode(5);
        TreeNode t6 = new TreeNode(6);
        TreeNode t7 = new TreeNode(7);
        t1.left = t2;
        t1.right = t3;
        t3.right = t6;
        t2.left = t4;
        t2.right = t5;
        t4.left = t7;
        printTreeAll(t1);
    }

结果正确:1 ,2 3 ,4 5 6 ,7 ,

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值