zoukankan      html  css  js  c++  java
  • 剑指offer(39)平衡二叉树

    题目描述

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。

    题目分析

    第一种方法:

      正常思路,应该会获得节点的左子树和右子树的高度,然后比较高度差是否小于1。

      可是这样有一个问题,就是节点重复遍历了,影响效率了。

    第二种方法:

      改进办法就是在求高度的同时判断是否平衡,如果不平衡就返回-1,否则返回树的高度。
      并且当左子树高度为-1时,就没必要去求右子树的高度了,可以直接一路返回到最上层了
     

    代码

    第一种:

    function IsBalanced_Solution(pRoot) {
      if (pRoot == null) return true;
      let leftLen = TreeDepth(pRoot.left);
      let rightLen = TreeDepth(pRoot.right);
      return Math.abs(rightLen - leftLen) <= 1 && IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right);
    }
    function TreeDepth(pRoot) {
      if (pRoot == null) return 0;
      let leftLen = TreeDepth(pRoot.left);
      let rightLen = TreeDepth(pRoot.right);
      return Math.max(leftLen, rightLen) + 1;
    }

    第二种:

    function IsBalancedSolution(pRoot) {
      return TreeDepth(pRoot) !== -1;
    }
    function TreeDepth(pRoot) {
      if (pRoot === null) return 0;
      const leftLen = TreeDepth(pRoot.left);
      if (leftLen === -1) return -1;
      const rightLen = TreeDepth(pRoot.right);
      if (rightLen === -1) return -1;
      return Math.abs(leftLen - rightLen) > 1 ? -1 : Math.max(leftLen, rightLen) + 1;
    }
  • 相关阅读:
    嵊泗
    窗函数介绍
    射频与微波测量之失真参数
    C# 文件与路径操作
    史密斯圆图
    Winform 关闭Form而不销毁Form的内存
    射频与微波测量之S参数
    东极岛
    C#中正则表达式解析字符串信息
    射频微波相关公式
  • 原文地址:https://www.cnblogs.com/wuguanglin/p/IsBalanced_Solution.html
Copyright © 2011-2022 走看看