[路飞]_LeetCode_226. 翻转二叉树

题目

翻转一棵二叉树。

示例:

输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
复制代码

输出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1
复制代码

来源:力扣(LeetCode)leetcode-cn.com/problems/in…

解题思路

  1. 用分治的思想
  2. 把根节点的左右子树互换
  3. 再递归把左、右子树翻转

2021-12-14 at 16.47.53.gif

代码实现

var invertTree = function(root) {
  if (!root) return root;
  //左右子树互换
  [root.left, root.right] = [root.right, root.left]

  invertTree(root.left)
  invertTree(root.right)

  return root
};
复制代码

如有错误欢迎指出,欢迎一起讨论!

猜你喜欢

转载自juejin.im/post/7041544722842091551