题目:
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

示例 2:
输入:root = [2,1,3]
输出:[2,3,1]

示例 3:
输入:root = []
输出:[]
提示:
树中节点数目范围在 [0, 100] 内
-100 <= Node.val <= 100
思路:
反转一颗空树 结果还是一颗空树。
对于根为 root, 左子树为 left, 右子树为 right的树来说,
它的反转树是:
根为 root, 左子树为 left的反转树, 右子树为 right的反转树 的树。
解答:
/**
* 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;
}
// 叶节点(无左子树,也无右子树)
if (!root.left && !root.right) {
return root;
}
// 递归
const right = invertTree(root.left);
const left = invertTree(root.right);
// 后序遍历
root.left = left;
root.right = right;
return root;
};

本文介绍了一种翻转二叉树的算法实现,通过递归方式交换每个节点的左右子树来完成整个二叉树的翻转。该算法适用于二叉树节点数量在0到100之间的场景,且节点值范围在-100到100之间。
458

被折叠的 条评论
为什么被折叠?



