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 nL 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;
        }
      
    }
}

 

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 11:47
点赞 评论 收藏
分享
这是什么操作什么意思,这公司我服了...
斯派克spark:意思是有比你更便宜的牛马了
点赞 评论 收藏
分享
06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
墨西哥大灰狼:如果你的校友卤馆还在的话,他肯定会给你建议的,可是卤馆注销了@ 程序员卤馆
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务