JZ77按之字形顺序打印二叉树

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 {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if(pRoot==null)return res; //这里要求返回thelist而不是null
        
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        
        queue.offer(pRoot);
        int count = 1;
        while(!queue.isEmpty()){            
            ArrayList<Integer> list = new ArrayList<Integer>();
            int size = queue.size();
            
            for(int i=0;i<size;i++){
                TreeNode temp = queue.poll();
                    if(count%2==0){
                        //从右边到左插入
                    list.add(0,temp.val);
                    }else{
                        list.add(temp.val);
                    }
                if(temp.left!=null){
                    queue.offer(temp.left);
                }
                if(temp.right!=null){
                    queue.offer(temp.right);
                }
            }
            
            res.add(list);
            count++;
        }
        return res;    
    }

}


/**

import java.util.*;
public class HelloWorld {
    public static void main(String []args) {
       System.out.println("Hello World!");
		 LinkedList<String> list = new LinkedList<String>();  
		list.add(0,"a");
		list.add(0,"b");
		list.add(0,"c");
		System.out.println("------------------");  
		list.add("d");
		list.add("e");
		list.add("f");
		
		 for (String str: list) {  
		  System.out.println(str);  
		}  
    }

**/

相关推荐

  1. ,堆(顺序结构)

    2024-03-18 01:08:06       55 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-18 01:08:06       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-18 01:08:06       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-18 01:08:06       87 阅读
  4. Python语言-面向对象

    2024-03-18 01:08:06       96 阅读

热门阅读

  1. Rust 01.变量、类型、函数

    2024-03-18 01:08:06       35 阅读
  2. Redis集群原理解析

    2024-03-18 01:08:06       40 阅读
  3. C++面试100问(十)

    2024-03-18 01:08:06       44 阅读
  4. python内置函数 L

    2024-03-18 01:08:06       43 阅读
  5. 京东按关键字搜索商品 API 返回值说明

    2024-03-18 01:08:06       44 阅读
  6. OpenWRT (LEDE) 镜像使用帮助

    2024-03-18 01:08:06       45 阅读
  7. 双向链表的实现

    2024-03-18 01:08:06       42 阅读
  8. python简单web框架介绍

    2024-03-18 01:08:06       43 阅读
  9. python--scrapy 保存数据到 mongodb

    2024-03-18 01:08:06       43 阅读