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

 

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:28
点赞 评论 收藏
分享
10-28 11:04
已编辑
美团_后端实习生(实习员工)
一个2人:我说几个点吧,你的实习经历写的让人觉得毫无含金量,你没有挖掘你需求里的 亮点, 让人觉得你不仅打杂还摆烂。然后你的简历太长了🤣你这个实习经历看完,估计没几个人愿意接着看下去, sdk, 索引这种东西单拎出来说太顶真了兄弟,好好优化下简历吧
点赞 评论 收藏
分享
11-01 20:03
已编辑
门头沟学院 算法工程师
Amazarashi66:这种也是幸存者偏差了,拿不到这个价的才是大多数
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务