• 【剑指offer】32-2 从上到下打印二叉树 II


    32-2 从上到下打印二叉树 II

    面试题32 - II. 从上到下打印二叉树 II

    难度简单17

    从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

    例如:

    给定二叉树: [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7
    

    返回其层次遍历结果:

    [
      [3],
      [9,20],
      [15,7]
    ]
    

    1.递归

    //递归
    List<List<Integer>> list = new ArrayList();
    
    public List<List<Integer>> levelOrder(TreeNode root) {
        recur(root,0);
        return list;
    }
    
    public void recur(TreeNode root,int k){
        //终止条件
        if(root != null){
            if(list.size()<=k){
                list.add(new ArrayList());
            }
            list.get(k).add(root.val);
            recur(root.left,k+1);
            recur(root.right,k+1);
        }
    }
    

    2.队列+迭代

      public List<List<Integer>> levelOrder(TreeNode root) {
                List<List<Integer>> result = new ArrayList<>();
                Queue<TreeNode> queue = new LinkedList<>();
                //添加根节点
                queue.add(root);
                while(!queue.isEmpty()){
                    List<Integer> list = new ArrayList<>();
                    int cnt = queue.size();
                    while(cnt-- > 0){
                        TreeNode t = queue.poll();//弹出首节点
                        if(t == null){
                            continue;
                        }
                        list.add(t.val);
                        queue.add(t.left);
                        queue.add(t.right);
                    }
                    if(list.size() != 0){
                        result.add(list);
                    }
                }
                return result;
            }
    
  • 相关阅读:
    JDBC
    MySQL 事务
    MySQL 处理海量数据时一些优化查询速度方法
    MySQL 分支和循环结构
    MySQL 分页查询和存储过程
    Oracle PL/SQL异常、存储过程和触发器
    Oracle PL/SQL游标
    mysql主键问题
    spring-springmvc code-based
    AOP实现原理
  • 原文地址:https://www.cnblogs.com/qxlxi/p/12860636.html
Copyright © 2020-2023  润新知