1. 镜像二叉树
题目描述: 请完成一个函数,输入一个二叉树,该函数输出它的镜像。 例如输入: 4 / \ 2 7 / \ / \ 1 3 6 9 镜像输出: 4 / \ 7 2 / \ / \ 9 6 3 1
示例 1: 输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {TreeNode}*/var mirrorTree = function(root) {if(!root) return null;var left = mirrorTree(root.left);var right = mirrorTree(root.right);root.left = right;root.right = left;return root;};
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {TreeNode}*/var mirrorTree = function(root) {if(!root) return null;let stack = [root];while(stack.length != 0){let node = stack.pop();if(node.left) stack.push(node.left);if(node.right) stack.push(node.right);let temp = node.left;node.left = node.right;node.right = temp;}return root;};
2. 平衡二叉树
题目描述: 输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。 示例 1: 给定二叉树 [3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7 返回 true 。
示例 2: 给定二叉树 [1,2,2,3,3,null,null,4,4] 1 / \ 2 2 / \ 3 3 / \ 4 4 返回 false 。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {boolean}*/let maxDepth = function(root){if(!root) return 0;else return Math.max(maxDepth(root.left),maxDepth(root.right))+1;}var isBalanced = function(root) {if(!root) return true;let left = maxDepth(root.left);let right = maxDepth(root.right);if(Math.abs(left-right)>1)return false;return isBalanced(root.left)&&isBalanced(root.right);};
