用JavaScript刷leetcode第226题-翻转二叉树

344 阅读1分钟

前言

本题将用递归来解题
两种思路:交换位置指 交换当前节点的左右子节点位置,翻转指翻转当前节点的左子树和右子树

  1. 先交换位置,再翻转
  2. 先翻转,再交换位置

一、题目描述

leetcode地址
示例:
输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

输出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

二、代码

2.1 先交换位置,再翻转

const invertTree = function (root) {
  // 递归结束条件
  if(root === null) return null

  // 交换当前节点的左右子节点
  const temp = root.left
  root.left = root.right
  root.right = temp

  // 翻转左、右子树
  invertTree(root.left)
  invertTree(root.right)

  return root
}

2.2 先翻转,再交换位置

const invertTree = function (root) {
  // 递归结束条件
  if(root === null) return null

  // 翻转左、右子树
  const left = invertTree(root.left)
  const right = invertTree(root.right)

  // 交换当前节点左、右子节点位置
  root.left = right
  root.right = left

  return root
}