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

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {TreeNode}
  11. */
  12. var mirrorTree = function(root) {
  13. if(!root) return null;
  14. var left = mirrorTree(root.left);
  15. var right = mirrorTree(root.right);
  16. root.left = right;
  17. root.right = left;
  18. return root;
  19. };
  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {TreeNode}
  11. */
  12. var mirrorTree = function(root) {
  13. if(!root) return null;
  14. let stack = [root];
  15. while(stack.length != 0){
  16. let node = stack.pop();
  17. if(node.left) stack.push(node.left);
  18. if(node.right) stack.push(node.right);
  19. let temp = node.left;
  20. node.left = node.right;
  21. node.right = temp;
  22. }
  23. return root;
  24. };

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

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {boolean}
  11. */
  12. let maxDepth = function(root){
  13. if(!root) return 0;
  14. else return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
  15. }
  16. var isBalanced = function(root) {
  17. if(!root) return true;
  18. let left = maxDepth(root.left);
  19. let right = maxDepth(root.right);
  20. if(Math.abs(left-right)>1)
  21. return false;
  22. return isBalanced(root.left)&&isBalanced(root.right);
  23. };

3. 搜索二叉树