前端-树

66 阅读1分钟

实现二叉树

class TreeNode {
  constructor (val) {
    this.val = val
    this.left = null
    this.right = null
  }
}

class Tree {
  constructor () {
    this.root = null
  }

  insert = function (val) {
    let node = new TreeNode(val)
    if (!this.root) {
      this.root = node
    } else {
      this.insertNode(this.root, node)
    }
  }

  insertNode = function (node, newNode) {
    if (node.val > newNode.val) { // 根节点值>左子树的值,格式保持统一
      if (!node.left) {
        node.left = newNode
      } else {
        this.insertNode(node.left, newNode)
      }
    } else {
      if (!node.right) {
        node.right = newNode
      } else {
        this.insertNode(node.right, newNode)
      }
    }
  }
}

二叉树的最大深度

  • 递归实现
function maxDepth (root) { // 获取二叉树的最大深度
  if (!root) {
    return 0
  } else {
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
  }
}

操作指定的二叉树,将其变换为源二叉树的镜像

源二叉树的镜像,指的就是左右子树交换位置

在这里插入图片描述

function mirror (root) { // 获取源二叉树的镜像
  if (!root) {
    return
  } else {
    let temp = root.left
    root.left = root.right
    root.right = temp
    mirror(root.left)
    mirror(root.right)
  }
  return root
}

判断二叉树是否是对称二叉树

对称二叉树是当前二叉树和二叉树的镜像一样

在这里插入图片描述

// 判断对称二叉树
function isSymmetric (root) {
  if (!root) {
    return true
  }
  return isSym(root.left, root.right)
}

function isSym (left, right) { // 给根节点左边使用根左右   根节点右侧使用根右左,比较对应的节点,一致则为对称
  if (left === null && right === null) {
    return true
  }

  if (left === null || right === null) {
    return false
  }

  if (left.val !== right.val) {
    return false
  }

  return isSym(left.left, right.right) && isSym(left.right, right.left)
}