2022.3.15

反转二叉树

输入

 4

/ 2 7 / \ / 1 3 6 9 输出

 4

/ 7 2 / \ / 9 6 3 1 节点的构造函数 /**

  • Definition for a binary tree node.

  • function TreeNode(val, left, right) {

  • this.val = (val===undefined ? 0 : val)
  • this.left = (left===undefined ? null : left)
  • this.right = (right===undefined ? null : right)
  • } */

var invertTree = function(root) {
    // 递归 终止条件
    if (root == null) {
        return root
    }
    // 递归的逻辑
    [root.left, root.right] = [invertTree(root.right), invertTree(root.left)]
    return root
}

最后更新于

这有帮助吗?