5.二叉树 | 左程云算法笔记

269 阅读4分钟

两个单链表相交的一系列问题

【题目】给定两个可能有环也可能无环的单链表,头节点head1和head2。请实现一个函数,如果两个链表相交,请返回相交的第一个节点。如果不相交,返回null

【要求】如果两个链表长度之和为N,时间复杂度请达到O(N),额外空间复杂度请达到O(1)。

public class Solution {

    public static class Node {
        public int value;
        public Node next;

        public Node(int data) {
            this.value = data;
        }
    }

    //两个可能有环或无环的单链表相交问题
    public static Node getIntersectNode(Node head1, Node head2) {
        if(head1 == null || head2 == null) return null;
        Node loop1 = getLoopNode(head1);
        Node loop2 = getLoopNode(head2);

//        两个无环单链表相交情况
        if (loop1 == null && loop2 == null){
            return noLoop(head1,head2);
        }

//        两个有环单链表相交情况
        if (loop1 != null && loop2 != null){
            return bothLoop(head1,loop1,head2,loop2);
        }
//        一个有环单链表和一个无环单链表绝对不会相交
        return null;
    }

//    获得一个链表的入环节点
    public static Node getLoopNode(Node head) {
//        少于三个节点的链表一定无环
        if(head == null || head.next == null || head.next.next == null) return null;
        Node slow = head.next;
        Node fast = head.next.next;
        while (slow != fast){
            if (fast.next == null || fast.next.next == null) return null;
            fast = fast.next.next;
            slow = slow.next;
        }
//        当找到快慢指针在环内相遇后,让其中一个指针再从head前进,另一个从交点前进,则再次相遇的点为入环节点
        fast = head;
        while (slow != fast){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

//    两个无环单链表相交
    public static Node noLoop(Node head1, Node head2) {
        Node cur1 = head1;
        Node cur2 = head2;
//        n 为两个链表相差的长度
        int n = 0;
        while (cur1.next != null){
            n++;
            cur1 = cur1.next;
        }
        while (cur2.next != null){
            n--;
            cur2 = cur2.next;
        }
//       两个无环单链表的末尾节点不相同一定不相交
        if (cur1 != cur2) return null;
//        cur1为较长链表的头结点 cur2为短的链表头结点
        cur1 = n > 0 ? head1 : head2;
        cur2 = cur1 == head1 ? head2 : head1;
        n = Math.abs(n);
        while (n > 0){
            n--;
            cur1 = cur1.next;
        }
        while (cur1 != cur2){
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        return cur1;
    }


    public static Node bothLoop(Node head1, Node loop1, Node head2, Node loop2) {
        if (head1 == null || head2 == null) return null;

        Node cur1 = null;
        Node cur2 = null;
//        入环节点相同相当于两个无环单链表相交的情况
        if(loop1 == loop2){
            cur1 = head1;
            cur2 = head2;
            int n = 0;
            while (cur1 != loop1) {
                n++;
                cur1 = cur1.next;
            }
            while (cur2 != loop2) {
                n--;
                cur2 = cur2.next;
            }
            cur1 = n > 0 ? head1 : head2;
            cur2 = cur1 == head1 ? head2 : head1;
            n = Math.abs(n);
            while (n != 0) {
                n--;
                cur1 = cur1.next;
            }
            while (cur1 != cur2) {
                cur1 = cur1.next;
                cur2 = cur2.next;
            }
            return cur1;
        }else {
            cur1 = loop1.next;
            while (cur1 != loop1){
                if (cur1 == loop2) return loop1;
                cur1 = cur1.next;
            }
            return null;
        }
    }

    public static void main(String[] args) {
        // 1->2->3->4->5->6->7->null
        Node head1 = new Node(1);
        head1.next = new Node(2);
        head1.next.next = new Node(3);
        head1.next.next.next = new Node(4);
        head1.next.next.next.next = new Node(5);
        head1.next.next.next.next.next = new Node(6);
        head1.next.next.next.next.next.next = new Node(7);

        // 0->9->8->6->7->null
        Node head2 = new Node(0);
        head2.next = new Node(9);
        head2.next.next = new Node(8);
        head2.next.next.next = head1.next.next.next.next.next; // 8->6
      System.out.println(getIntersectNode(head1, head2).value);

        // 1->2->3->4->5->6->7->4...
        head1 = new Node(1);
        head1.next = new Node(2);
        head1.next.next = new Node(3);
        head1.next.next.next = new Node(4);
        head1.next.next.next.next = new Node(5);
        head1.next.next.next.next.next = new Node(6);
        head1.next.next.next.next.next.next = new Node(7);
        head1.next.next.next.next.next.next = head1.next.next.next; // 7->4

        // 0->9->8->2...
        head2 = new Node(0);
        head2.next = new Node(9);
        head2.next.next = new Node(8);
        head2.next.next.next = head1.next; // 8->2
        System.out.println(getIntersectNode(head1, head2).value);

        // 0->9->8->6->4->5->6..
        head2 = new Node(0);
        head2.next = new Node(9);
        head2.next.next = new Node(8);
        head2.next.next.next = head1.next.next.next.next.next; // 8->6
        System.out.println(getIntersectNode(head1, head2).value);

    }

}

二叉树的先序、中序、后序的递归和非递归遍历

public class Solution {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

//    先序遍历的递归方式
    public static void preOrderRecur(Node head) {
        if (head == null) {
            return;
        }
        System.out.print(head.value + " ");
        preOrderRecur(head.left);
        preOrderRecur(head.right);
    }

//中序遍历的递归方式
    public static void inOrderRecur(Node head) {
        if (head == null) {
            return;
        }
        inOrderRecur(head.left);
        System.out.print(head.value + " ");
        inOrderRecur(head.right);
    }

//后序遍历的递归方式
    public static void posOrderRecur(Node head) {
        if (head == null) {
            return;
        }
        posOrderRecur(head.left);
        posOrderRecur(head.right);
        System.out.print(head.value + " ");
    }

//先序遍历的非递归方式
    public static void preOrderUnRecur(Node head) {
        System.out.print("pre-order: ");
        if (head != null) {
            Stack<Node> stack = new Stack<Node>();
            stack.add(head);
            while (!stack.isEmpty()) {
                head = stack.pop();
                System.out.print(head.value + " ");
                if (head.right != null) {
                    stack.push(head.right);
                }
                if (head.left != null) {
                    stack.push(head.left);
                }
            }
        }
        System.out.println();
    }
//中序遍历的非递归方式 每颗子树,整棵树左边界进栈,依次弹出的过程中,对弹出节点的右树周而复始
    public static void inOrderUnRecur(Node head) {
        System.out.print("in-order: ");
        if (head != null) {
            Stack<Node> stack = new Stack<Node>();
            while (!stack.isEmpty() || head != null) {
                if (head != null) {
                    stack.push(head);
                    head = head.left;
                } else {
                    head = stack.pop();
                    System.out.print(head.value + " ");
                    head = head.right;
                }
            }
        }
        System.out.println();
    }

//    后序遍历的非递归方式 一个放栈一个收栈 弹出cur到收栈里,再把cur的孩子先左后右再放入栈中,最后把收栈里的所有节点倒出来
    public static void posOrderUnRecur1(Node head) {
        System.out.print("pos-order: ");
        if (head != null) {
            Stack<Node> s1 = new Stack<Node>();
            Stack<Node> s2 = new Stack<Node>();
            s1.push(head);
            while (!s1.isEmpty()) {
                head = s1.pop();
                s2.push(head);
                if (head.left != null) {
                    s1.push(head.left);
                }
                if (head.right != null) {
                    s1.push(head.right);
                }
            }
            while (!s2.isEmpty()) {
                System.out.print(s2.pop().value + " ");
            }
        }
        System.out.println();
    }

    public static void posOrderUnRecur2(Node h) {
        System.out.print("pos-order: ");
        if (h != null) {
            Stack<Node> stack = new Stack<Node>();
            stack.push(h);
            Node c = null;
            while (!stack.isEmpty()) {
                c = stack.peek();
                if (c.left != null && h != c.left && h != c.right) {
                    stack.push(c.left);
                } else if (c.right != null && h != c.right) {
                    stack.push(c.right);
                } else {
                    System.out.print(stack.pop().value + " ");
                    h = c;
                }
            }
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Node head = new Node(5);
        head.left = new Node(3);
        head.right = new Node(8);
        head.left.left = new Node(2);
        head.left.right = new Node(4);
        head.left.left.left = new Node(1);
        head.right.left = new Node(7);
        head.right.left.left = new Node(6);
        head.right.right = new Node(10);
        head.right.right.left = new Node(9);
        head.right.right.right = new Node(11);

        // recursive
        System.out.println("==============recursive==============");
        System.out.print("pre-order: ");
        preOrderRecur(head);
        System.out.println();
        System.out.print("in-order: ");
        inOrderRecur(head);
        System.out.println();
        System.out.print("pos-order: ");
        posOrderRecur(head);
        System.out.println();

        // unrecursive
        System.out.println("============unrecursive=============");
        preOrderUnRecur(head);
        inOrderUnRecur(head);
        posOrderUnRecur1(head);
        posOrderUnRecur2(head);

    }

}

直观打印二叉树(辅助方法,不用学习)

public class Code02_PrintBinaryTree {

   public static class Node {
      public int value;
      public Node left;
      public Node right;

      public Node(int data) {
         this.value = data;
      }
   }

   public static void printTree(Node head) {
      System.out.println("Binary Tree:");
      printInOrder(head, 0, "H", 17);
      System.out.println();
   }

   public static void printInOrder(Node head, int height, String to, int len) {
      if (head == null) {
         return;
      }
      printInOrder(head.right, height + 1, "v", len);
      String val = to + head.value + to;
      int lenM = val.length();
      int lenL = (len - lenM) / 2;
      int lenR = len - lenM - lenL;
      val = getSpace(lenL) + val + getSpace(lenR);
      System.out.println(getSpace(height * len) + val);
      printInOrder(head.left, height + 1, "^", len);
   }

   public static String getSpace(int num) {
      String space = " ";
      StringBuffer buf = new StringBuffer("");
      for (int i = 0; i < num; i++) {
         buf.append(space);
      }
      return buf.toString();
   }

   public static void main(String[] args) {
      Node head = new Node(1);
      head.left = new Node(-222222222);
      head.right = new Node(3);
      head.left.left = new Node(Integer.MIN_VALUE);
      head.right.left = new Node(55555555);
      head.right.right = new Node(66);
      head.left.left.right = new Node(777);
      printTree(head);

      head = new Node(1);
      head.left = new Node(2);
      head.right = new Node(3);
      head.left.left = new Node(4);
      head.right.left = new Node(5);
      head.right.right = new Node(6);
      head.left.left.right = new Node(7);
      printTree(head);

      head = new Node(1);
      head.left = new Node(1);
      head.right = new Node(1);
      head.left.left = new Node(1);
      head.right.left = new Node(1);
      head.right.right = new Node(1);
      head.left.left.right = new Node(1);
      printTree(head);

   }

}

二叉树的层序遍历和获得最大宽度

public class Solution {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    // 二叉树层序遍历
    public void width(Node head){
        if (head == null) return;
        Queue<Node> queue = new LinkedList<>();
        queue.add(head);
        while (!queue.isEmpty()){
            Node cur = queue.poll();
            System.out.println(cur.value);
            if (cur.left != null){
                queue.add(cur.left);
            }
            if (cur.right != null){
                queue.add(cur.right);
            }
        }
    }

//寻找二叉树最大宽度数 准备一个哈希表,来记录<节点,节点所在的层数>
    public static int getMaxWidth(Node head) {
        if(head == null) return 0;
        HashMap<Node,Integer> levelMap = new HashMap<>();
        levelMap.put(head,1);
        Queue<Node> queue = new LinkedList<>();
        queue.add(head);
        int curLevel = 1;
        int curLevelNodes = 0;
        int maxWidth = Integer.MIN_VALUE;
        while (!queue.isEmpty()){
            Node cur = queue.poll();
//            出于一个层级,节点数加一
            if (levelMap.get(cur) == curLevel){
                curLevelNodes++;
            }else {
                maxWidth = Math.max(maxWidth,curLevelNodes);
                curLevel++;
                curLevelNodes = 0;
            }

            if (cur.left != null){
                queue.add(cur.left);
                levelMap.put(cur.left,levelMap.get(cur) + 1);
            }

            if (cur.right != null){
                queue.add(cur.right);
                levelMap.put(cur.right,levelMap.get(cur) + 1);
            }
        }

        return maxWidth;
    }





    public static void main(String[] args) {
        Node head = new Node(5);
        head.left = new Node(3);
        head.right = new Node(8);
        head.left.left = new Node(2);
        head.left.right = new Node(4);
        head.left.left.left = new Node(1);
        head.right.left = new Node(7);
        head.right.left.left = new Node(6);
        head.right.right = new Node(10);
        head.right.right.left = new Node(9);
        head.right.right.right = new Node(11);

        System.out.println(getMaxWidth(head));

    }

}