请完成一个函数,输入一个二叉树,该函数输出它的镜像
书上给了一个示意图:
显而易见,从根节点开始,交换左右子树的位置;再照这个思路向下处理子树节点。
/*** 二叉树结点类*/class Node {constructor(value, left = null, right = null) {this.value = value;this.left = left;this.right = right;}}/*** 二叉树镜像函数* @param {Node} root*/function mirrorBinaryTree(root) {if (root === null) {return;}// 交换左右节点let left = root.left;root.left = root.right;root.right = left;// 继续处理左右子树if (root.left) {mirrorBinaryTree(root.left);}if (root.right) {mirrorBinaryTree(root.right);}}/*** 以下是测试代码*/const root = new Node(0, new Node(1, new Node(3)), new Node(2));mirrorBinaryTree(root);console.log(root);