2022-10-09 -- binary tree 二叉树

Summary

  1. 二叉树结构
  2. 二叉树递归遍历
    2.1递归序
    2.2先序遍历 -- 根左右
    2.3中序遍历 -- 左根右
    2.4后序遍历 -- 左右根
  3. 二叉树非递归遍历(任何递归都可以改成非递归)
    3.1非递归先序遍历 -- 根左右
    3.2非递归后序遍历 -- 左右根
    3.3非递归中序遍历 -- 左根右
  4. 二叉树广度优先遍历BFS
  5. 二叉树相关概念及实现判断
    5.1 判断是否是搜索二叉树 -- 98 Validate Binary Search Tree (medium)
    5.2 判断是否是完全二叉树 958 Check Completeness of a Binary Tree --(medium)
    5.3 判断是否为满二叉树--套路解题
    5.4判断是否为平衡二叉树--110 Balanced Binary Tree (easy)
    5.5二叉树套路 -- 解决树形DP问题
  6. 最低公共祖先--236 Lowest Common Ancestor of a Binary Tree (medium)
  7. 二叉树中找到一个节点的后继节点 -- 510 Inorder Successor in BST II(medium)
  8. 二叉树序列化和反序列化 -- 297 Serialize and Deserialize Binary Tree (hard)
  9. 折纸问题

1. 二叉树结构:


 // Definition for a binary tree node.
  public class TreeNode {
      int val;
      TreeNode left;//pointer to left child
      TreeNode right;//pointer to right child
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

2. 二叉树递归遍历

2.1 递归序

public static void f(Node head){
    //1
    if(head == null){
        return;
    }
    //1
    f(head.left);
    //2
    //2
    f(head.right);
    //3
    //3
}

递归时,一个点一定会被调3次,第一次时到,第二次是从左孩子回来,第三次是从右孩子回来。
顺序如下:


二叉树递归遍历顺序

2.2 先序遍历 -- 根左右

1245367 --> 递归序时,第一次到达此处时print

public static void preOrderRecur(Node head){
    //1
    if(head == null){
        return;
    }
    //1
    System.out.print(head.value + "");
    f(head.left);
    f(head.right);

}

2.3 中序遍历 -- 左根右

4251637 --> 递归序时,第二次到达此处时print

public static void inOrderRecur(Node head){
    if(head == null){
        return;
    }
    f(head.left);
    //2
    System.out.print(head.value + "");
    //2
    f(head.right);
}

2.4 后序遍历 -- 左右根

4526731 --> 递归序时,第三次到达此处时print

public static void posOrderRecur(Node head){
    if(head == null){
        return;
    }
    f(head.left);
    f(head.right);
    //3
    System.out.print(head.value + "");
    //3
}

3. 二叉树非递归遍历(任何递归都可以改成非递归)

3.1非递归先序遍历 -- 根左右

  • 首先把root放入栈中
  • 从栈中弹出一个节点cur
  • 打印cur
  • 把该点的孩子,先右后左放入(如果有),没有就什么也不做
  • 重复上述步骤
public static void PreOrderUnRecur(Node head){
    if (head != null){
        Stack stack = new Stack();
        stack.add(head);
        while(!stack.isEmpty()){
            head = stack.pop();
            System.out.println(head.val+" ");
            if(head.right != null){
                stack.push(head.right);
            }
            if(head.left != null){
                statck.push(head.left);
            }
        }
    }
}

3.2非递归后序遍历 -- 左右根

  • 首先把root放入栈中
  • 从栈中弹出一个节点cur
  • 把cur放入辅助栈中
  • 把该点的孩子,先左后右放入(如果有),没有就什么也不做
  • 重复上述步骤,直到最后
  • 打印辅助栈
public static void posOrderUnRecur(Node head){
    if (head != null){
        Stack stack1 = new Stack();
        Stack stack2 = new Stack();
        stack1.push(head);
        while(!stack1.isEmpty()){
            head = stack1.pop();
            stack2.push(head);
            if(head.left != null){
                stack1.push(head.right);
            }
            if(head.right != null){
                statck1.push(head.left);
            }
        }
        while(!stack2.isEmpty()){
            System.out.print(stack2.pop().val + " ");
        }
    }
}

3.3非递归中序遍历 -- 左根右

  • 整个树的左边界依次入栈
  • 依次弹出,弹出时打印
  • 若弹出节点有右树重复以上步骤(右树的整个左边界一次入栈)
  • 打印栈
public static void inOrderUnRecur(Node head){
    if(head != null){
        Stack stack = new Stack();
        while(!stack.isEmpty() || head != null){
            if(head !=null){
                stack.push(head);
                head = head.left;//把左边界全部入栈
            }else{//head变空了,左边界全部入栈
                head = stack.pop();//弹出节点
                System.out.print(head.val + " ");
                head = head.right;//节点变成右孩子,此时head如果有左孩子,就非空,继续把左边界压入栈
            }
        }
    }
}

4. 二叉树广度优先遍历BFS

  • 使用queue队列(先进先出)
  • 先放入root
  • 从queue中弹出一个节点
  • 打印,并先放入左孩子,再放入右孩子
  • 循环
public static void bfs(Node head){
    if(head == null){
        return;
    }
    Queue queue = new LinkedList();
    queue.add(head);
    while(!queue.isEmpty){
        Node cur = queue.poll();
        System.out.print(cur.val + " ");
        if(cur.left != null){
            queue.add(cur.left);
        }
        if(cur.right != null){
            queue.add(cur.right);
        }
    }
}

例题:求一颗二叉树宽度 -- leetcode 662 Maximum Width of Binary Tree (medium)

5. 二叉树相关概念及实现判断

5.1 判断是否是搜索二叉树 -- 98 Validate Binary Search Tree (medium)

A valid BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

思路:中序遍历,搜索二叉树一定升序

class Solution{
    public boolean isValidBST(TreeNode head){
        List inOrderList = new ArrayList<>();
        process(head, inOrderList);
        for (int i = 0; i < inOrderList.size() -1; i++){
            if(inOrderList.get(i).val >= inOrderList.get(i+1).val){
                return false;
            }
        }
        return true;
    }
    public void process(TreeNode head, List inOrderList){
        if (head == null){
            return;
        }
        process(head.left, inOrderList);
        inOrderList.add(head);
        process(head.right, inOrderList);
        
    }
}

套路思路:需要左右树信息:1. 是否是搜索二叉树 (左max +右min)--> 2.max 3. min

class Solution{
    public boolean isValidBST(TreeNode head){
        if(head == null){
            return true;
        }
        return process(head).isBST;
    }
    
    public class Info{
        public boolean isBST;
        public int max;
        public int min;

        
        public Info(boolean iss, int ma, int mi){//constructor
            isBST = iss;
            max = ma;
            min = mi;
        }
    }
    
    public Info process(TreeNode x){
        if(x == null){
            return null;
        }
        
        Info leftData = process(x.left);
        Info rightData = process(x.right);
        
        int min = x.val;
        int max = x.val;
        if(leftData != null){
            min = Math.min(min, leftData.min);
            max = Math.max(max, leftData.max);
        }
        if(rightData != null){
            min = Math.min(min, rightData.min);
            max = Math.max(max, rightData.max);
        }
        
        boolean isBST = true;
        
        if(leftData != null && (!leftData.isBST || leftData.max >= x.val)){
            isBST = false;
        }
        if(rightData != null && (!rightData.isBST || x.val >= rightData.min)) {
            isBST = false;
        }
       
        return new Info(isBST, max, min);
    }
}

原因:递归是对每个点的要求应该相同

5.2 判断是否是完全二叉树 958 Check Completeness of a Binary Tree --(medium)

In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible.
除了最后一层都是满的,且最后一层在从左到右正在变满
思路:层序遍历
1. 任意节点,只有右孩子没有左孩子--false
2. 在1不违规是,遇到第一个左右孩子不双全的情况,接下来遇到的所有节点都必须是叶子
3.如果符合12,就是完全二叉树

 class Solution {
    public boolean isCompleteTree(TreeNode head) {
        if (head == null){
            return true;
        }
        Queue queue = new LinkedList<>();
        boolean leaf = false;//判断是否遇到第一个左右孩子不双全的节点,遇到前都是false,遇到后都是true
        TreeNode l = null;
        TreeNode r = null;
        queue.add(head);
        while(!queue.isEmpty()){
            head = queue.poll();
            l = head.left;
            r = head.right;
            if((leaf && (l != null || r != null))||(l == null && r != null)){
                //条件2 || 条件1
                //已经遇到了不双全的叶节点,但当前节点竟然后孩子 || 只有右孩子没有左孩子
                
                return false;
            }
            if(l != null){
                queue.add(l);
            }
            if(r != null){
                queue.add(r);
            }
            if(l == null || r == null){//可能会被多次标记,但只要标记过后就是true
                leaf = true;
            }
        }
        return true;
    }
}

5.3 判断是否为满二叉树--套路解题

除最后一层无任何子节点外,每一层上的所有结点都有两个子结点的二叉树。
套路分析:需要左右树的信息:1.深度,2.节点个数

class Solution{
  public boolean isFull(TreeNode head){
      if(head == null){
          return true;
      }
      Info data = process(head);
      return data.nodes == ((1 << data.height) - 1);//深度为k 的满二叉树必有2^k-1 个节点
  }
  
  public class Info{
      public int height;
      public int nodes;
      
      public Info(int h, int n){//constructor
          height = h;
          nodes = n;
      }
  }
  
  public Info process(TreeNode x){
      if(x == null){
          return new Info(0,0);
      }
      Info leftData = process(x.left);
      Info rightData = process(x.right);
      int height = Math.max(leftData.height, rightData.height) + 1;
      int nodes = leftData.nodes + rightData.nodes + 1;
      return new Info(height, nodes);
  }
}

5.4 判断是否为平衡二叉树--110 Balanced Binary Tree (easy)

它的左子树和右子树的高度之差(平衡因子)的绝对值不超过1且它的左子树和右子树都是一颗平衡二叉树。
套路分析:需要左右子树的信息:1.是否是平衡二叉树,2.高度

class Solution{
    public boolean isBalanced(TreeNode head){
        if(head == null){
            return true;
        }
        return process(head).isBalanced;
    }
    
    public class Info{
        public int height;
        public boolean isBalanced;
        
        public Info(int h, boolean isb){//constructor
            height = h;
            isBalanced = isb;
        }
    }
    
    public Info process(TreeNode x){
        if(x == null){
            return new Info(0, true);
        }
        Info leftData = process(x.left);
        Info rightData = process(x.right);
        int height = Math.max(leftData.height, rightData.height) + 1;
        boolean isBalanced = leftData.isBalanced && rightData.isBalanced && Math.abs(leftData.height - rightData.height) < 2;
        return new Info(height, isBalanced);
    }
}

5.5二叉树套路 -- 解决树形DP问题

思路:返回左树信息+右树信息并整合,且继续递归

6. 最低公共祖先--236 Lowest Common Ancestor of a Binary Tree (medium)

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA : “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
思路:用HashMap储存<节点,父节点>,递归遍历所有点,都记下来。然后对点1,用hashset把他所有的祖先都找出来,一直找到head。然后对点2,也是一直找,并判断此时的祖先在不在点1 的set中

class Solution{
    public TreeNode lowestCommonAncestor(TreeNode head, TreeNode o1, TreeNode o2){
        HashMap fatherMap = new HashMap<>();//记录这个点和这个点的父节点
        fatherMap.put(head,head);//traverse方法无法放入head的父,所以手动规定
        traverse(head, fatherMap);
        HashSet set1 = new HashSet<>();
        set1.add(o1);
        TreeNode cur = o1;
        while(cur != fatherMap.get(cur)){//只有head可以等于自己的父
            //不是父时,往上找
            set1.add(cur);
            cur = fatherMap.get(cur);
        }
        set1.add(head);//最后加入head
        
        HashSet set2 = new HashSet<>();
        TreeNode curt = o2;
        while(curt != fatherMap.get(curt)){
            set2.add(curt);
            if(set1.contains(curt)){
                return curt;
            }
            curt = fatherMap.get(curt);
        }
            return head;
    }
    
    public void traverse(TreeNode head, HashMap fatherMap){
        if(head == null){
            return;
        }
        fatherMap.put(head.left, head);
        fatherMap.put(head.right, head);
        traverse(head.left, fatherMap);
        traverse(head.right, fatherMap);
    }
}

非常厉害的答案:
两种情况:

  1. 点1是点2的最低公共祖先,或点2是点1的最低公共祖先
  2. 点1和点2 不互为公共祖先,只能向上找才能找到最低公共祖先
    下面的代码两种情况都对,但并不是我能想出来的
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q){
            return root;
        }
            TreeNode left = lowestCommonAncestor (root.left, p, q);
            TreeNode right = lowestCommonAncestor (root.right, p, q);
            if(left != null && right != null){
                return root;
            }
            return left != null ? left : right;
        }
}

7. 二叉树中找到一个节点的后继节点 -- 510 Inorder Successor in BST II(medium)

Given a node in a binary search tree, return the in-order successor of that node in the BST. If that node has no in-order successor, return null.
The successor of a node is the node with the smallest key greater than node.val.
You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for Node:

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
}

后继节点:中序遍历排序后,本节点的下一个节点
(前驱节点:中序遍历排序后,本节点的上一个节点)
时间复杂度需要从O(N) 优化成O(K)K是两个点的真实距离
思路:
情况1: node有右树时,node后继节点是右树上的最左节点
情况2: node无右树时,往上找,一直找到一个点是其父节点的左孩子,此时node的后继节点就是找到点的父节点。若一直找不到,说明这个点是最右的点,return null

class Solution {
    public Node inorderSuccessor(Node node) {
        if(node == null){
            return node;
        }
        if(node.right != null){//情况1, 有右子树
            return getMostLeft(node.right);
        }else{//情况2:无右子树
            Node parent = node.parent;
            while(parent != null && parent.left != node){//当前节点有父节点,且当前节点是父节点的右孩子
                node = parent;
                parent = node.parent;//往上走
            }
            return parent;//当此节点为左节点,返回他的父节点。当遍历完成,到root时也不是左孩子,此时parent就是null,所以返回null
        }
        
        
    }
    
    public Node getMostLeft(Node node){
        if(node == null){
            return node;
        }
        while(node.left != null){//要判定有没有左孩子
            node = node.left;
        }
        return node;
    }
}

8. 二叉树序列化和反序列化 -- 297 Serialize and Deserialize Binary Tree (hard)

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

例子:先序遍历树,下划线_表示值的结束,#表示null


序列化例子
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode head) {
        if(head == null){
            return "#_";
        }
        String res = head.val + "_";
        res += serialize(head.left);
        res += serialize(head.right);
        return res;
}

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] values = data.split("_");
        Queue queue = new LinkedList();
        for(int i = 0; i != values.length; i++){
            queue.add(values[I]);
        }
        return reconnect(queue);
    }
    
    public TreeNode reconnect(Queue queue){
        String value = queue.poll();
        if(value.equals("#")){
            return null;
        }
        TreeNode head = new TreeNode(Integer.valueOf(value));
        head.left = reconnect(queue);
        head.right = reconnect(queue);
        return head;
    }
}

9. 折纸问题

请把纸条竖着放在桌⼦上,然后从纸条的下边向上⽅对折,压出折痕后再展开。此时有1条折痕,突起的⽅向指向纸条的背⾯,这条折痕叫做“下”折痕 ;突起的⽅向指向纸条正⾯的折痕叫做“上”折痕。如果每次都从下边向上⽅ 对折,对折N次。请从上到下计算出所有折痕的⽅向。给定折的次数n,请返回从上到下的折痕的数组,若为下折痕则对应元素为"down",若为上折痕则为"up"。


折痕可以形成二叉树

每一个左子树的头节点都是凹,右子树的头节点都是凸

最优解如下:空间复杂度O(N)

public void printAllFolds(int N){
    //主函数是1,凹
    printProcess(1, N, true);
}
//递归过程,来到某一节点
//i是节点层数,N是一共几层,down== true 凹,down == false 凸
public void printProcess(int i, int N, boolean down){
    if(i > N){//超过层数,return
        return;
    }
    printProcess(i + 1, N, true);
    //中序遍历
    System.out.println(down ? "凹" : "凸");
    
    printProcess(i + 1, N, false);
}

你可能感兴趣的:(2022-10-09 -- binary tree 二叉树)