226.Invert_Binary_Tree

25 年 7 月 1 日 星期二
116 字
1 分钟

226. 翻转二叉树

Screenshot 2026-03-07 at 10.40.00 am

先交换左右儿子或者先翻转都行

js
var 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
}
js
var invertTree = function (root) {
  if (root === null) {
    return null
  }
  ;[root.left, root.right] = [root.right, root.left] // 交换左右儿子
  invertTree(root.left) // 翻转左子树
  invertTree(root.right) // 翻转右子树
  return root
}

文章标题:226.Invert_Binary_Tree

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/226invert_binary_tree[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。