- Circular linked list
Set the speed pointer. If there is a ring, the slow pointer must catch up with the fast pointer; If there is no loop, the fast pointer becomes NULL
class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null) {return false;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast.next ! =null&& fast ! = slow) {if (fast == null) {
return false;
}
fast = fast.next.next;
slow = slow.next;
}
if (fast == slow) {
return true;
}
return false; }}Copy the code
- Binary tree forward traversal
Ideas:…
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> l = new ArrayList<>();
preorder(root, l);
return l;
}
public void preorder(TreeNode root, List<Integer> l) {
if (root == null) {
return; } l.add(root.val); preorder(root.left, l); preorder(root.right, l); }}Copy the code
- Backorder traversal of binary tree
Ideas:…
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> l = new ArrayList<>();
postorder(root, l);
return l;
}
public void postorder(TreeNode root, List<Integer> l) {
if (root == null) {
return; } postorder(root.left, l); postorder(root.right, l); l.add(root.val); }}Copy the code