• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

二叉树——四进阶面试题

武飞扬头像
笨笨在努力
帮助1

目录

1.根据先序和中序遍历结果还原二叉树

2.根据中序和后序遍历结果还原二叉树

3.从先序遍历还原二叉树 

4.从先序遍历输出为中序遍历结果

5.二叉树的最近公共祖先

6.根据二叉树创建字符串

7.递增顺序搜索树

8.二叉树的完全性检验

9.二叉搜索树转双向链表 


1.根据先序和中序遍历结果还原二叉树

105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com)

重建二叉树_牛客题霸_牛客网 (nowcoder.com)

 遍历到的前序作为根节点,通过找中序遍历中该节点的位置确定左右子树的范围;

不断遍历前序节点进行递归,不断缩小范围,递归的过程实则就是在还原连接左右子树

  1.  
    class Solution {
  2.  
    int index;
  3.  
    public TreeNode buildTree(int[] preorder, int[] inorder) {
  4.  
    return buildTreeHelper(preorder,inorder,0,preorder.length);
  5.  
    }
  6.  
    // 借助中序遍历在【left,right]范围内找左右子树,还原二叉树并返回根节点,
  7.  
    public TreeNode buildTreeHelper(int[] preorder,int[] inorder,int left,int right){
  8.  
    // 边界
  9.  
    if(left > right){
  10.  
    return null;
  11.  
    }
  12.  
    if(index == preorder.length){
  13.  
    return null;
  14.  
    }
  15.  
    // 依据前序遍历创建根节点
  16.  
    TreeNode root = new TreeNode(preorder[index]);
  17.  
    index ;
  18.  
    // 找到该根节点在中序遍历中的位置
  19.  
    int position = find(root.val,inorder);
  20.  
    // 递归左子树
  21.  
    root.left = buildTreeHelper(preorder,inorder,left,position - 1);
  22.  
    // 递归右子树
  23.  
    root.right = buildTreeHelper(preorder,inorder,position 1,right);
  24.  
    return root;
  25.  
    }
  26.  
     
  27.  
     
  28.  
    private int find(int value, int[] inorder) {
  29.  
    for (int i = 0; i < inorder.length; i ) {
  30.  
    if(inorder[i] == value){
  31.  
    return i;
  32.  
    }
  33.  
    }
  34.  
    return -1;
  35.  
     
  36.  
     
  37.  
     
  38.  
    }
  39.  
    }
学新通

2.根据中序和后序遍历结果还原二叉树

106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com)

下面这种做法跟上面第一题整体思路一致,稍稍不同,这种做法更具普适性,对于根据前中还原,根据后中还原,都可套用这个模板 

下面这种做法,是对两个数组都在进行范围的缩小与确认

思路:

从后序遍历最后一个节点作为根节点开始,不断向前遍历,然后在中序遍历里确定该节点位置,由此确认中序遍历中左右子树的位置,再根据左右子树的个数,确定后序遍历结果中的左右子树的范围,递归左右即可。

  1.  
    public class Leetcode_T106_in_post {
  2.  
    public TreeNode buildTree(int[] inorder, int[] postorder) {
  3.  
    int n1 = inorder.length;
  4.  
    int n2 = postorder.length;
  5.  
    if(n1 == 0 || n2 == 0 || n1 != n2){
  6.  
    return null;
  7.  
    }
  8.  
    return buildHelper(inorder,postorder,0,inorder.length - 1,0,postorder.length - 1);
  9.  
    }
  10.  
     
  11.  
    private TreeNode buildHelper(int[] inorder, int[] postorder, int inorderStart, int inorderEnd, int postorderStart, int postorderEnd) {
  12.  
    if(inorderStart > inorderEnd || postorderStart > postorderEnd){
  13.  
    return null;
  14.  
    }
  15.  
    TreeNode newRoot = new TreeNode(postorder[postorderEnd]);
  16.  
    // 在中序遍历里找后序根的位置
  17.  
    for (int j = inorderStart; j <= inorderEnd; j ) {
  18.  
    if(inorder[j] == postorder[postorderEnd]){
  19.  
    int mid = j;
  20.  
    // 关键是找清左右子树在中序、后序遍历中的范围!!!画图清楚一点
  21.  
    newRoot.left = buildHelper(inorder,postorder,inorderStart,mid - 1,postorderStart,postorderStart mid - inorderStart - 1);
  22.  
    newRoot.right = buildHelper(inorder,postorder,mid 1,inorderEnd,postorderEnd - 1 - (inorderEnd - mid ) 1 ,postorderEnd - 1);
  23.  
    break;
  24.  
    }
  25.  
    }
  26.  
    // 返回根节点
  27.  
    return newRoot;
  28.  
    }
学新通

3.从先序遍历还原二叉树 

1028. 从先序遍历还原二叉树 - 力扣(LeetCode) (leetcode-cn.com)

同样是根据先序遍历结果还原二叉树,这道题较之第四题略显难一点,因为第四题借助递归即可实现,而这道题,递归不再适用,而要根据给出的每个节点的深度来构建二叉树

  • 记录每个节点的值
  • 记录每个节点的深度
  • 借助栈完成还原:如果栈内元素个数与待入栈元素的深度一致,说明,栈顶元素即为待入栈元素的父节点,如果不一致,说明待入栈元素是某个节点的右节点,所以栈内元素出栈直至找到父节点,并连接该关系
  1.  
    public TreeNode recoverFromPreorder(String traversal) {
  2.  
    // index是索引下标,遍历后移
  3.  
    int index = 0;
  4.  
    Deque<TreeNode> stack = new LinkedList<>();
  5.  
    while (index < traversal.length()) {
  6.  
    // 当遇到深度表示符
  7.  
    // depth记录每次遇到的节点的深度
  8.  
    int depth = 0;
  9.  
    while (traversal.charAt(index) == '-') {
  10.  
    depth ;
  11.  
    index ;
  12.  
    }
  13.  
    // val记录每次节点的值
  14.  
    int val = 0;
  15.  
    // 当遇到数字
  16.  
    while (index < traversal.length() && Character.isDigit(traversal.charAt(index))) {
  17.  
    val = val * 10 (traversal.charAt(index) - '0');
  18.  
    index ;
  19.  
    }
  20.  
     
  21.  
    // 此时,节点值为val,深度为depth
  22.  
    TreeNode node = new TreeNode(val);
  23.  
     
  24.  
    // 如果节点深度与栈内元素个数一样,则连接栈顶与左节点,并入栈(记得先判空)
  25.  
    if (depth == stack.size()) {
  26.  
    // 如果栈不为空,则连接左节点,如果栈为空,直接入栈
  27.  
    if (!stack.isEmpty()) {
  28.  
    stack.peek().left = node;
  29.  
    }
  30.  
    stack.push(node);
  31.  
    } else {
  32.  
    // 否则,说明遇到深度小的节点了,说明是栈内某节点的右节点
  33.  
    while (stack.size() != depth) {
  34.  
    stack.pop();
  35.  
    }
  36.  
    // 出栈到这里,说明栈顶是父节点
  37.  
    stack.peek().right = node;
  38.  
    stack.push(node);
  39.  
    }
  40.  
    }
  41.  
    // 最后返回根节点
  42.  
    while (stack.size() > 1) {
  43.  
    stack.pop();
  44.  
    }
  45.  
    return stack.peek();
  46.  
    }
学新通

4.从先序遍历输出为中序遍历结果

二叉树遍历_牛客题霸_牛客网 (nowcoder.com)

关键点是如何根据给出的先序遍历结果来还原二叉树:

先序遍历是根左右的顺序,我们还可以借助递归来实现:当遇到#说明是空节点,返回Null,然后按照根左右的顺序递归构建

  1.  
    import java.util.*;
  2.  
    public class Main{
  3.  
    private static int index = 0;
  4.  
    public static void main(String[] args){
  5.  
    Scanner scanner = new Scanner(System.in);
  6.  
    String s = scanner.next();
  7.  
    TreeNode root = buildTree(s);
  8.  
    midOrder(root);
  9.  
    }
  10.  
     
  11.  
    // 构建二叉树
  12.  
    public static TreeNode buildTree(String s){
  13.  
    if(s.charAt(index) == '#'){
  14.  
    return null;
  15.  
    }
  16.  
    // 如果不为null,则开始建节点
  17.  
    TreeNode node = new TreeNode(s.charAt(index));
  18.  
    index ;
  19.  
    node.left = buildTree(s);
  20.  
    index ;
  21.  
    node.right = buildTree(s);
  22.  
    return node;
  23.  
    }
  24.  
    // 中序遍历输出
  25.  
    public static void midOrder(TreeNode root){
  26.  
    if(root == null){
  27.  
    return;
  28.  
    }
  29.  
    // 左
  30.  
    midOrder(root.left);
  31.  
    // 根
  32.  
    System.out.print(root.value " ");
  33.  
    // 右
  34.  
    midOrder(root.right);
  35.  
    }
  36.  
     
  37.  
    }
  38.  
    class TreeNode{
  39.  
    char value;
  40.  
    TreeNode left;
  41.  
    TreeNode right;
  42.  
    public TreeNode(char value){
  43.  
    this.value = value;
  44.  
    }
  45.  
    }
学新通

5.二叉树的最近公共祖先

236. 二叉树的最近公共祖先 - 力扣(LeetCode) (leetcode-cn.com)

思路:

在最近公共节点处,有这么几种可能:

(1)p、q恰好在公共节点的一左一右

(2)最近公共节点即为p或q之一,另一个节点位于左或右

故而,我们可以在查找某节点的递归方法中顺便记录最近公共节点

这样定义:如果在左子树能找到p或者q,记作1,否则记作0;同样,如果能在右子树找到p或者q,再记为1,否则为0;同时,判断该根节点是否就是p或q,如果是也记作1,不是记作0,如果存在这三个数之和=2,说明该节点出发能找到p和q,最后,只需返回最近的即可。

  1.  
    class Solution {
  2.  
    private TreeNode ret;
  3.  
     
  4.  
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  5.  
    find(root, p, q);
  6.  
    return ret;
  7.  
    }
  8.  
     
  9.  
    // 在以node为根结点的子树中能否找到结点p或者q
  10.  
    public boolean find(TreeNode node, TreeNode p, TreeNode q) {
  11.  
    if (node == null) {
  12.  
    return false;
  13.  
    }
  14.  
    // 递归查找左子树
  15.  
    int left = find(node.left, p, q) ? 1 : 0;
  16.  
    // 递归查找右子树
  17.  
    int right = find(node.right, p, q) ? 1 : 0;
  18.  
    // 看是否根节点就是p或者q
  19.  
    int mid = (node == p || node == q) ? 1 : 0;
  20.  
    // 如果=2,说明p q一个在左子树一个在右子树或者一个是根节点另一个是左子树或右子树
  21.  
    if (left right mid == 2) {
  22.  
    ret = node;
  23.  
    }
  24.  
    return (left right mid) > 0;
  25.  
     
  26.  
    }
  27.  
    }
学新通

6.根据二叉树创建字符串

606. 根据二叉树创建字符串 - 力扣(LeetCode) (leetcode-cn.com)

关键是对括号的拼接:

先拼接根节点和左括号——》如果有左节点,接着正常拼接左节点(即递归左),递归左结束,加右括号——》如果没有左节点,则需要先判断是否有右节点——》如果有右节点,则空的左需要用一对括号代替,然后再去递归右子树——》如果没有右节点,说明左右节点都没有,无需再管

  1.  
    //你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
  2.  
    //空节点则用一对空括号 "()" 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
  3.  
    public class Leetcode_T606_Tree2Str {
  4.  
    StringBuilder s = new StringBuilder();
  5.  
     
  6.  
    public String tree2str(TreeNode root) {
  7.  
    if (root == null) {
  8.  
    return "";
  9.  
    }
  10.  
    // 先根结点
  11.  
    s.append(root.val);
  12.  
    // 当左子树不为空,正常拼接
  13.  
    if (root.left != null) {
  14.  
    s.append("(");
  15.  
    // 递归左子树
  16.  
    tree2str(root.left);
  17.  
    s.append(")");
  18.  
    } else {
  19.  
    // 当左子树为空,仅当右子树不为空时才添加()
  20.  
    if (root.right != null) {
  21.  
    s.append("()");
  22.  
    }
  23.  
    }
  24.  
    // 最后处理右子树
  25.  
    if (root.right != null) {
  26.  
    s.append("(");
  27.  
    tree2str(root.right);
  28.  
    s.append(")");
  29.  
    }
  30.  
    return s.toString();
  31.  
    }
  32.  
    }
学新通

7.递增顺序搜索树

897. 递增顺序搜索树 - 力扣(LeetCode) (leetcode-cn.com)

按左根右的顺序重新连接二叉树 

  • 递归左,找到左部分的头节点和尾节点,头节点用于方法的返回,尾节点则去和根节点进行连接;
  • 再递归右,将根节点与右部分连接
  1.  
    class Solution {
  2.  
    public TreeNode increasingBST(TreeNode root) {
  3.  
    if(root == null){
  4.  
    return null;
  5.  
    }
  6.  
    // 先左,记录左子树排列为递增顺序搜索树的头节点
  7.  
    TreeNode leftHead = increasingBST(root.left);
  8.  
    // 因为左部分接着要跟根节点连接,所以,我们需要找到左部分的尾节点
  9.  
    TreeNode leftTail = leftHead;
  10.  
    while(leftTail != null && leftTail.right != null){
  11.  
    leftTail = leftTail.right;
  12.  
    }
  13.  
    // 左部分要跟根节点连接,注意判空,有可能左部分为空
  14.  
    if(leftTail != null){
  15.  
    // 连接新线
  16.  
    leftTail.right = root;
  17.  
    // 断开之前的线,否则会形成闭环
  18.  
    root.left = null;
  19.  
    }
  20.  
    // 最后处理根节点与右部分的头节点的连接
  21.  
    TreeNode rightHead = increasingBST(root.right);
  22.  
    if(rightHead != null){
  23.  
    // 连线再断线
  24.  
    root.right = rightHead;
  25.  
    rightHead.left = null;
  26.  
    }
  27.  
    return leftHead == null ? root : leftHead;
  28.  
    }
  29.  
    }
学新通

8.二叉树的完全性检验

958. 二叉树的完全性检验 - 力扣(LeetCode) (leetcode-cn.com)

这道题其实就是让你判断给定的二叉树是否是完全二叉树

所以,让我们来分析下完全二叉树的特点,是的,可以发现,对于一棵完全二叉树,按层序遍历,当碰到第一个没有左孩子的节点时,必然,从该节点开始之后的所有节点一定必须得是叶子节点,否则,必然不满足完全二叉树的条件

从这个条件出发,我们在代码中可以引入一个boolean变量作为标志位,来判断是否到了叶子节点的交界点。状态一为默认状态,表明应当是左右孩子都有,当遇到第一个没有左孩子的节点时,切换为状态二,状态二以后的节点必须既无左孩子也无右孩子 

  1.  
    class Solution {
  2.  
    public boolean isCompleteTree(TreeNode root) {
  3.  
    boolean state = false;
  4.  
    if(root == null){
  5.  
    return true;
  6.  
    }
  7.  
    Deque<TreeNode> queue = new LinkedList<>();
  8.  
    queue.offer(root);
  9.  
    // 层序遍历
  10.  
    while(!queue.isEmpty()){
  11.  
    TreeNode cur = queue.poll();
  12.  
    // 如果是状态一,则只要有左右孩子为空的就不是完全二叉树
  13.  
    if(!state){
  14.  
    // 如果左右子树都不为空,则正常继续层序遍历
  15.  
    if(cur.left != null && cur.right != null){
  16.  
    queue.offer(cur.left);
  17.  
    queue.offer(cur.right);
  18.  
    }else if(cur.right != null){
  19.  
    // 如果左子树为空,右子树不为空,直接返回false
  20.  
    return false;
  21.  
    }else if(cur.left != null){
  22.  
    // 如果左子树不为空,右子树为空,则调整状态为状态二
  23.  
    state = true;
  24.  
    queue.offer(cur.left);
  25.  
    }else{
  26.  
    // 最后的情况,左右孩子都为空,说明碰到了第一个叶子节点,也调整状态为状态二
  27.  
    state = true;
  28.  
    }
  29.  
    }else{
  30.  
    // 否则是状态二,则必须左右孩子全部为空才是完全二叉树
  31.  
    if(cur.left != null || cur.right != null){
  32.  
    return false;
  33.  
    }
  34.  
    }
  35.  
    }
  36.  
    // 如果遍历完,都未返回false,说明是完全二叉树
  37.  
    return true;
  38.  
    }
  39.  
    }
学新通

9.二叉搜索树转双向链表 

二叉搜索树与双向链表_牛客题霸_牛客网 (nowcoder.com)

其实这道题和上面的第七道题基本一模一样,思路一致,只是连线稍微有点区别而已。

思路还是:

找到左的头节点,尾节点;

将左的尾同根节点连接;

再递归找到右的头节点;

将根节点与右的头节点连接;

最后返回左的头节点(如果左为空,返回根节点)

  1.  
    public class Solution {
  2.  
    public TreeNode Convert(TreeNode pRootOfTree) {
  3.  
    if(pRootOfTree == null){
  4.  
    return null;
  5.  
    }
  6.  
    // 先递归左
  7.  
    // 找到左部分的头节点和尾节点
  8.  
    TreeNode leftHead = Convert(pRootOfTree.left);
  9.  
    TreeNode leftTail = leftHead;
  10.  
    while(leftTail != null && leftTail.right != null){
  11.  
    leftTail = leftTail.right;
  12.  
    }
  13.  
    // 将左与根连接
  14.  
    if(leftTail != null){
  15.  
    leftTail.right = pRootOfTree;
  16.  
    pRootOfTree.left = leftTail;
  17.  
    }
  18.  
    // 再递归右子树
  19.  
    TreeNode rightHead = Convert(pRootOfTree.right);
  20.  
    // 将根节点与右部分连接
  21.  
    if(rightHead != null){
  22.  
    pRootOfTree.right = rightHead;
  23.  
    rightHead.left = pRootOfTree;
  24.  
    }
  25.  
    // 最后返回头节点
  26.  
    return leftHead == null ? pRootOfTree : leftHead;
  27.  
    }
  28.  
    }
学新通

呼~二叉树还是得再多练练

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggfjeg
系列文章
更多 icon
同类精品
更多 icon
继续加载