第四课:二叉树

左程云算法初级班 第四课

  1. 实现二叉树的先序、中序、后序遍历,包括递归方式和非递归方式

在这里插入图片描述
上图中,左图为二叉树,右图为遍历结点过程

  • 先序遍历:第一次到达结点时输出该节点值;中序遍历:第二次到达结点时输出该节点值;后序遍历:第三次到达结点时输出该节点值;
  • 递归方式:对于先序比遍历,先打印当前结点的值,再对该结点的左孩子进行先序遍历,最后对右该结点的孩子进行先序遍历;对于中序比遍历,先对该结点的左孩子进行中序遍历,再打印当前结点的值,最后对右该结点的孩子进行中序遍历;对于后序比遍历,先对该结点的左孩子进行后序遍历,再对右该结点的孩子进行后序遍历,最后打印当前结点的值;
  • 递归方式代码:
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 + " ");
 }
  • 非递归方式:对于先序遍历,使用栈存储结点信息,栈不为空时,每次pop出栈顶的结点并打印,若该结点存在左右孩子结点,则先将右孩子压入栈,再将左孩子压入栈,这样在pop时肯定先左后右,如此实现先序遍历的顺序逻辑;对于中序遍历,准备一个栈,首先将该二叉树每层的最左边的结点信息压入栈内,再在pop出每个结点时都去检查右孩子结点是否存在,若存在则压入栈,并将以该右孩子结点为根节点的子树的每层的最左边的结点信息压入栈重复之前过程实现后序遍历的顺序逻辑,具体实现逻辑看代码;对于后序遍历,准备两个栈s1和s2,借助s1栈将所有结点以后序遍历的倒序压入s2中,然后pop出s2栈中的所有结点,如此实现后序遍历的顺序逻辑;
  • 非递归方式代码:
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();
 }

 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();
 }
  1. 如何直观的打印一颗二叉树
  • 工具辅助函数,不是重点,借助使用即可。代码如下:
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();
 }
  1. 在二叉树中找到一个节点的后继节点

【题目】 现在有一种新的二叉树节点类型如下:
public class Node { public int value; public Node left;
public Node right; public Node parent;
public Node(int data) { this.value = data; }
}
该结构比普通二叉树节点结构多了一个指向父节点的parent指针。假设有一 棵Node类型的节点组成的二叉树,树中每个节点的parent指针都正确地指向 自己的父节点,头节点的parent指向null。只给一个在二叉树中的某个节点 node,请实现返回node的后继节点的函数。在二叉树的中序遍历的序列中, node的下一个节点叫作node的后继节点。

  • 在中序遍历中判断后继节点逻辑:1,若该结点的右孩子为null,则该结点的后继结点为该结点右子树上最后一层最左边的结点;2,若该结点的右孩子不为null且该结点的父节点的左孩子为该结点,则该结点的后继结点为该结点的父结点;3,若该结点的右孩子不为null且该结点的父节点的左孩子不为该结点,则该结点继续找父结点的父结点直到符合情况2或者一直找到父结点为null时返回找到的最后的父结点为后继结点。
  • 代码:
public static Node getSuccessorNode(Node node) {
     if (node == null) {
         return node;
     }
     if (node.right != null) {
         return getLeftMost(node.right);
     } else {
         Node parent = node.parent;
         while (parent != null && parent.left != node) {
             node = parent;
             parent = node.parent;
         }
         return parent;
     }
 }

 public static Node getLeftMost(Node node) {
     if (node == null) {
         return node;
     }
     while (node.left != null) {
         node = node.left;
     }
     return node;
 }
  1. 介绍二叉树的序列化和反序列化
    • 按照先序遍历的方法,将二叉树序列化,null用#表示,各结点之间用!进行分隔;在反序列化时,通过!将序列化的字符串进行分割,并将分割后的结点放入队列,然后重建二叉树;
    • 代码:
    public static String serialByPre(Node head) {
            if (head == null) {
                return "#!";
            }
            String res = head.value + "!";
            res += serialByPre(head.left);
            res += serialByPre(head.right);
            return res;
        }
    
        public static Node reconByPreString(String preStr) {
            String[] values = preStr.split("!");
            Queue<String> queue = new LinkedList<String>();
            for (int i = 0; i != values.length; i++) {
                queue.offer(values[i]);
            }
            return reconPreOrder(queue);
        }
    
        public static Node reconPreOrder(Queue<String> queue) {
            String value = queue.poll();
            if (value.equals("#")) {
                return null;
            }
            Node head = new Node(Integer.valueOf(value));
            head.left = reconPreOrder(queue);
            head.right = reconPreOrder(queue);
            return head;
        }
        ```
        * 用分层遍历的方法实现序列化与反序列化
        * 代码:
        ```java
    public static String serialByLevel(Node head) {
            if (head == null) {
                return "#!";
            }
            String res = head.value + "!";
            Queue<Node> queue = new LinkedList<Node>();
            queue.offer(head);
            while (!queue.isEmpty()) {
                head = queue.poll();
                if (head.left != null) {
                    res += head.left.value + "!";
                    queue.offer(head.left);
                } else {
                    res += "#!";
                }
                if (head.right != null) {
                    res += head.right.value + "!";
                    queue.offer(head.right);
                } else {
                    res += "#!";
                }
            }
            return res;
        }
    
        public static Node reconByLevelString(String levelStr) {
            String[] values = levelStr.split("!");
            int index = 0;
            Node head = generateNodeByString(values[index++]);
            Queue<Node> queue = new LinkedList<Node>();
            if (head != null) {
                queue.offer(head);
            }
            Node node = null;
            while (!queue.isEmpty()) {
                node = queue.poll();
                node.left = generateNodeByString(values[index++]);
                node.right = generateNodeByString(values[index++]);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            return head;
        }
    
        public static Node generateNodeByString(String val) {
            if (val.equals("#")) {
                return null;
            }
            return new Node(Integer.valueOf(val));
        }
    
  2. 折纸问题

【题目】 请把一段纸条竖着放在桌子上,然后从纸条的下边向上方对折1次,压出折痕后展开。此时 折痕是凹下去的,即折痕突起的方向指向纸条的背面。如果从纸条的下边向上方连续对折2 次,压出折痕后展开,此时有三条折痕,从上到下依次是下折痕、下折痕和上折痕。给定一 个输入参数N,代表纸条都从下边向上方连续对折N次,请从上到下打印所有折痕的方向。 例如:N=1时,打印: downN=2时,打印: down down up

  • 该问题用二叉树的中序遍历方法实现,当对折次数大于1时,每次对折,就在对折中线上边产生新的折痕,这样的对折不妨假象为一棵二叉树,每个结点的左孩子值为down,右孩子值为up,进行中序遍历,可得从上到下的折痕;
  • 代码:
public static void printAllFolds(int N) {
     printProcess(1, N, true);
 }

 public static void printProcess(int i, int N, boolean down) {
     if (i > N) {
         return;
     }
     printProcess(i + 1, N, true);
     System.out.println(down ? "down " : "up ");
     printProcess(i + 1, N, false);
 }

 public static void main(String[] args) {
     int N = 4;
     printAllFolds(N);
 }
  1. 判断一棵二叉树是否是平衡二叉树
    • 平衡二叉树:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树
    • 代码:
    public static boolean isBalance(Node head) {
            boolean[] res = new boolean[1];
            res[0] = true;
            getHeight(head, 1, res);
            return res[0];
        }
    
        public static int getHeight(Node head, int level, boolean[] res) {
            if (head == null) {
                return level;
            }
            int lH = getHeight(head.left, level + 1, res);
            if (!res[0]) {
                return level;
            }
            int rH = getHeight(head.right, level + 1, res);
            if (!res[0]) {
                return level;
            }
            if (Math.abs(lH - rH) > 1) {
                res[0] = false;
            }
            return Math.max(lH, rH);
        }
    
  2. 判断一棵树是否是搜索二叉树、判断一棵树是否是完全二叉树
    • 搜索二叉树:它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
    • 二叉树的中序遍历的结果是依次递增的,那这个二叉树就是搜索二叉树;
    • 完全二叉树:所有的叶结点都出现在第k层或k-l层(层次最大的两层);对任一结点,如果其右子树的最大层次为L,则其左子树的最大层次为L或L+l。
    • 1,遇到结点,有右孩子没左孩子,return false;2,如果遇到结点,有左没右或左右都没有,则后面遇到的结点都必须是叶结点,否则return false;
    • 代码:
    public static boolean isBST(Node head) {
            if (head == null) {
                return true;
            }
            boolean res = true;
            Node pre = null;
            Node cur1 = head;
            Node cur2 = null;
            while (cur1 != null) {
                cur2 = cur1.left;
                if (cur2 != null) {
                    while (cur2.right != null && cur2.right != cur1) {
                        cur2 = cur2.right;
                    }
                    if (cur2.right == null) {
                        cur2.right = cur1;
                        cur1 = cur1.left;
                        continue;
                    } else {
                        cur2.right = null;
                    }
                }
                if (pre != null && pre.value > cur1.value) {
                    res = false;
                }
                pre = cur1;
                cur1 = cur1.right;
            }
            return res;
        }
    
        public static boolean isCBT(Node head) {
            if (head == null) {
                return true;
            }
            Queue<Node> queue = new LinkedList<Node>();
            boolean leaf = false;
            Node l = null;
            Node r = null;
            queue.offer(head);
            while (!queue.isEmpty()) {
                head = queue.poll();
                l = head.left;
                r = head.right;
                if ((leaf && (l != null || r != null)) || (l == null && r != null)) {
                    return false;
                }
                if (l != null) {
                    queue.offer(l);
                }
                if (r != null) {
                    queue.offer(r);
                } else {
                    leaf = true;
                }
            }
            return true;
        }
    
  3. 已知一棵完全二叉树,求其结点的个数

要求:时间复杂度低于O(N),N为这棵树的结点个数

  • 判断当前结点的右子树的高度是否为二叉树高度减1,若是,则当前结点的左子树为满二叉树,若不是,则当前结点的右子树为满二叉树,满二叉树的结点个数为2^L-1,L为满二叉树的高度,如此递归可求解。
  • 代码:
public static int nodeNum(Node head) {
     if (head == null) {
         return 0;
     }
     return bs(head, 1, mostLeftLevel(head, 1));
 }

 public static int bs(Node node, int l, int h) {
     if (l == h) {
         return 1;
     }
     if (mostLeftLevel(node.right, l + 1) == h) {
         return (1 << (h - l)) + bs(node.right, l + 1, h);
     } else {
         return (1 << (h - l - 1)) + bs(node.left, l + 1, h);
     }
 }

 public static int mostLeftLevel(Node node, int level) {
     while (node != null) {
         level++;
         node = node.left;
     }
     return level - 1;
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Timothy Cui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值