把二叉树打印成多行

题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
类似上一题
思路:利用层次遍历,但加入本层levelque和下一层nextlevel,res存放最终值
1.根节点加入levelque中
2.while leveque:针对每层创建一个nextlevel(存入左子树和右子树),curvalue存放当前层的值
3.然后将curvalue加入res中,nextlevel给level

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表[[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        levelque=[pRoot]
        res=[]
        while levelque:
            curvalue=[]
            nextlevel=[]
            for i in levelque:
                curvalue.append(i.val)
                if  i.left:
                    nextlevel.append(i.left)
                if  i.right:
                    nextlevel.append(i.right)
            if curvalue:
                res.append(curvalue)
            levelque=nextlevel
        return res

层次遍历

import java.util.*;


/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res=new ArrayList<>();
        ArrayList<Integer> list=new ArrayList<>();
        if(pRoot==null) return res;
        Queue<TreeNode> q=new LinkedList<>();
        int curcount=0;
        int nextcount=1;
        q.add(pRoot);
        while(!q.isEmpty()){
            TreeNode cur=q.poll();
            curcount+=1;
            list.add(cur.val);
            if(cur.left!=null)q.add(cur.left);
            if(cur.right!=null) q.add(cur.right);
            if(curcount==nextcount){
                res.add(list);
                curcount=0;
                nextcount=q.size();
                list=new ArrayList<Integer>();
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值