2019.7.22
zyb大概是凉凉了
继续加油啦
============================分割线===========================
Given a binary tree, return the preorder traversal of its nodes' values.先序遍历 输入到list中
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(root == null){
return list;
}
help(root , list);
return list;
}
public void help(TreeNode root , ArrayList<Integer> list){
list.add(root.val);
if(root.left != null){
help(root.left , list);
}
if(root.right != null){
help(root.right , list);
}
}
}
Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-2→…
You must do this in-place without altering the nodes' values.
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null){
return;
}else{
if(head.next == null || head.next.next == null){
return;
}
}
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode after = slow.next;
slow.next = null;
ListNode pre = null;
while(after != null){
ListNode next = after.next;
after.next = pre;
pre = after;
after = next;
}
//反转过链表之后,after已经到了null,此时的pre才是新链表的头节点
after = pre;
while(head != null && after != null){
ListNode headnext = head.next;
ListNode afternext = after.next;
head.next = after;
head = headnext;
after.next = head;
after = afternext;
}
}
}