码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 103 二叉树的锯齿形层次遍历 以及 LinkedList

时间:2019-11-14 13:44:54      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:列表   bool   zigzag   exception   stat   ack   链表实现   面试题   节点   

LeetCode103 二叉树的锯齿形层次遍历:

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

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

3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:[[3],[20,9],[15,7]]

import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(root==null)
            return res;
        // tmp记录当前层的节点val
        List<Integer> tmp = new ArrayList<>();
        // num记录下一层的节点个数; count表示当前层还有几个节点没有遍历
        int num=0, count=1;
        // 约定: flag==false表示当前层是奇数层; flag==true表示当前层是偶数层; root是奇数层
        boolean flag=false;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode cur;
        while(!queue.isEmpty()){
            //奇数层:弹出队首元素; 左右孩子加入队尾
            if(flag==false){
                cur = queue.pollFirst();
                tmp.add(cur.val);
                if(cur.left!=null){
                    queue.addLast(cur.left);
                    num++;
                }
                if(cur.right!=null){
                    queue.addLast(cur.right);
                    num++;
                }
            }
            //偶数层:弹出队尾元素; 右左孩子加入队首
            else{
                cur = queue.pollLast();
                tmp.add(cur.val);
                if(cur.right!=null){
                    queue.addFirst(cur.right);
                    num++;
                }
                if(cur.left!=null){
                    queue.addFirst(cur.left);
                    num++;
                }
            }
            count--;
            if(count==0){
                count = num;
                num = 0;
                flag = !flag;
                res.add(new ArrayList<Integer>(tmp));
                tmp.clear();
            }
        }
        return res;
    }
}

作者:littlehaes
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/solution/javaji-bai-100-zhi-yong-yi-ge-dui-lie-shi-xian-zig/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

--------------------------以下是LinkedList介绍---------------------------------------

LinkedList类是双向列表,列表中的每个节点都包含了对前一个和后一个元素的引用.
LinkedList的构造函数如下
1. public LinkedList():  ——生成空的链表
2. public LinkedList(Collection col):  复制构造函数
1、获取链表的第一个和最后一个元素

import java.util.LinkedList;
 
public class LinkedListTest{
  public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();
    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");
 
 
    System.out.println("链表的第一个元素是 : " + lList.getFirst());
    System.out.println("链表最后一个元素是 : " + lList.getLast());
  }
}

2、获取链表元素  

for (String str: lList) {
      System.out.println(str);
    }

3、从链表生成子表

List subl = lList.subList(1, 4);
    System.out.println(subl);
    lst.remove(2);
    System.out.println(lst);
    System.out.println(lList);

4、添加元素:添加单个元素
 如果不指定索引的话,元素将被添加到链表的最后.
  public boolean add(Object element)
  public boolean add(int index, Object element)
也可以把链表当初栈或者队列来处理:
  public boolean addFirst(Object element)
  public boolean addLast(Object element)
  addLast()方法和不带索引的add()方法实现的效果一样.

import java.util.LinkedList;
 
public class LinkedListTest{
  public static void main(String[] a) {
    LinkedList list = new LinkedList();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add("D");
    list.addFirst("X");
    list.addLast("Z");
    System.out.println(list);
  }
}

5、删除元素

public Object removeFirst()
public Object removeLast()
import java.util.LinkedList;
 
 
public class MainClass {
  public static void main(String[] a) {
 
 
    LinkedList list = new LinkedList();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add("D");
    list.removeFirst();
    list.removeLast();
    System.out.println(list);
  }
}

6、使用链表实现栈效果

import java.util.LinkedList;
public class MainClass {
  public static void main(String[] args) {
    StackL stack = new StackL();
    for (int i = 0; i < 10; i++)
      stack.push(i);
    System.out.println(stack.top());
    System.out.println(stack.top());
    System.out.println(stack.pop());
    System.out.println(stack.pop());
    System.out.println(stack.pop());
  }
}
class StackL {
  private LinkedList list = new LinkedList();
  public void push(Object v) {
    list.addFirst(v);
  }
  public Object top() {
    return list.getFirst();
  }
  public Object pop() {
    return list.removeFirst();
  }
}

7、使用链表来实现队列效果

import java.util.LinkedList;
public class MainClass {
  public static void main(String[] args) {
    Queue queue = new Queue();
    for (int i = 0; i < 10; i++)
      queue.put(Integer.toString(i));
    while (!queue.isEmpty())
      System.out.println(queue.get());
  }
}
class Queue {
  private LinkedList list = new LinkedList();
  public void put(Object v) {
    list.addFirst(v);
  }
  public Object get() {
    return list.removeLast();
  }
  public boolean isEmpty() {
    return list.isEmpty();
  }
}

8、将LinkedList转换成ArrayList

ArrayList<String> arrayList = new ArrayList<String>(linkedList);
    for (String s : arrayList) {
      System.out.println("s = " + s);
    }

9、删掉所有元素:清空LinkedList
    lList.clear();
10、删除列表的首位元素

import java.util.LinkedList;
public class Main {
  public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();
    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");
    System.out.println(lList);
        //元素在删除的时候,仍然可以获取到元素
    Object object = lList.removeFirst();
    System.out.println(object + " has been removed");
    System.out.println(lList);
    object = lList.removeLast();
    System.out.println(object + " has been removed");
    System.out.println(lList);
  }
}

11、根据范围删除列表元素

import java.util.LinkedList;
public class Main {
  public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();
    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");
    System.out.println(lList);
    lList.subList(2, 5).clear();
    System.out.println(lList);
  }
}

12、删除链表的特定元素

import java.util.LinkedList;
public class Main {
  public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();
    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");
    System.out.println(lList);
    System.out.println(lList.remove("2"));//删除元素值=2的元素
    System.out.println(lList);
    Object obj = lList.remove(2);  //删除第二个元素
    System.out.println(obj + " 已经从链表删除");
    System.out.println(lList);
  }
}

13、将LinkedList转换为数组,数组长度为0

import java.util.LinkedList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    List<String> theList = new LinkedList<String>();
    theList.add("A");
    theList.add("B");
    theList.add("C");
    theList.add("D");
    String[] my = theList.toArray(new String[0]);
    for (int i = 0; i < my.length; i++) {
      System.out.println(my[i]);
    }
  }
}

14、将LinkedList转换为数组,数组长度为链表长度

import java.util.LinkedList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    List<String> theList = new LinkedList<String>();
    theList.add("A");
    theList.add("B");
    theList.add("C");
    theList.add("D");
    String[] my = theList.toArray(new String[theList.size()]);
    for (int i = 0; i < my.length; i++) {
      System.out.println(my[i]);
    }
  }
}

15、将LinkedList转换成ArrayList

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    LinkedList<String> myQueue = new LinkedList<String>();
    myQueue.add("A");
    myQueue.add("B");
    myQueue.add("C");
    myQueue.add("D");
    List<String> myList = new ArrayList<String>(myQueue);
    for (Object theFruit : myList)
      System.out.println(theFruit);
  }
}

16、实现栈

import java.util.Collections;
import java.util.LinkedList;
public class Main {
  public static void main(String[] argv) throws Exception {
    LinkedList stack = new LinkedList();
    Object object = "";
    stack.addFirst(object);
    Object o = stack.getFirst();
    stack = (LinkedList) Collections.synchronizedList(stack);
  }
}

17、实现队列

import java.util.LinkedList;
public class Main {
  public static void main(String[] argv) throws Exception {
    LinkedList queue = new LinkedList();
    Object object = "";
    // Add to end of queue
    queue.add(object);
    // Get head of queue
    Object o = queue.removeFirst();
  }
}

18 、同步方法

import java.util.Collections;
import java.util.LinkedList;
public class Main {
  public static void main(String[] argv) throws Exception {
    LinkedList queue = new LinkedList();
    Object object = "";
    queue.add(object);
    Object o = queue.removeFirst();
    queue = (LinkedList) Collections.synchronizedList(queue);
  }
}

19、查找元素位置

import java.util.LinkedList;
 
public class Main {
  public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();
    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");
    lList.add("2");
    System.out.println(lList.indexOf("2"));
    System.out.println(lList.lastIndexOf("2"));
  }
}

20、替换元素

import java.util.LinkedList;
 
public class Main {
  public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();
    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");
    System.out.println(lList);
    lList.set(3, "Replaced");//使用set方法替换元素,方法的第一个参数是元素索引,后一个是替换值
    System.out.println(lList);
  }
}

21、链表添加对象

import java.util.LinkedList;
class Address {
  private String name;
  private String street;
  private String city;
  private String state;
  private String code;
  Address(String n, String s, String c, String st, String cd) {
    name = n;
    street = s;
    city = c;
    state = st;
    code = cd;
  }
  public String toString() {
    return name + " " + street + " " + city + " " + state + " " + code;
  }
}
 
 
class MailList {
  public static void main(String args[]) {
    LinkedList<Address> ml = new LinkedList<Address>();
    ml.add(new Address("A", "11 Ave", "U", "IL", "11111"));
    ml.add(new Address("R", "11 Lane", "M", "IL", "22222"));
    ml.add(new Address("T", "8 St", "C", "IL", "33333"));
    for (Address element : ml)
      System.out.println(element + "\n");
  }
}

22、确认链表是否存在特定元素

import java.util.LinkedList;
 
 
public class Main {
  public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();
    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");
    if (lList.contains("4")) {
      System.out.println("LinkedList contains 4");
    } else {
      System.out.println("LinkedList does not contain 4");
    }
  }
}

23、根据链表元素生成对象数组

Object[] objArray = lList.toArray();
for (Object obj: objArray) {
   System.out.println(obj);
}

24、链表多线程

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
class PrepareProduction implements Runnable {
  private final List<String> queue;
  PrepareProduction(List<String> q) {
    queue = q;
  }
  public void run() {
    queue.add("1");
    queue.add("done");
  }
}
class DoProduction implements Runnable {
  private final List<String> queue;
  DoProduction(List<String> q) {
    queue = q;
  }
  public void run() {
    String value = queue.remove(0);
    while (!value.equals("*")) {
      System.out.println(value);
      value = queue.remove(0);
    }
  }
}
public class Main {
  public static void main(String[] args) throws Exception {
    List q = Collections.synchronizedList(new LinkedList<String>());
    Thread p1 = new Thread(new PrepareProduction(q));
    Thread c1 = new Thread(new DoProduction(q));
    p1.start();
    c1.start();
    p1.join();
    c1.join();
  }
}

Java 常见面试题之“Arraylist和Linkedlist的区别”

版权声明:本文为CSDN博主「qq是一枚程序媛」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42468526/article/details/81178698

 

LeetCode 103 二叉树的锯齿形层次遍历 以及 LinkedList

标签:列表   bool   zigzag   exception   stat   ack   链表实现   面试题   节点   

原文地址:https://www.cnblogs.com/doyi111/p/11856492.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!