前端嘛 Logo
前端嘛

0226.翻转二叉树

题目链接

题目大意

让二叉树的每个节点的左右子树调换位置

思路与代码

递归

/**
 * 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)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function (root) {
  if (!root) return null;
  [root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
  return root;
};
  • 空间复杂度:O(h) h 为树的高度

  • 时间复杂度:O(n)