首页 > 试题广场 >

平衡树判定

[编程题]平衡树判定
  • 热度指数:17 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
实现一个函数检查一棵树是否平衡。对于这个问题而言,平衡指的是这棵树任意两个叶子结点到根结点的距离之差不大于1
示例1

输入

{1,2,3,#,#,4,#,#,5}

输出

false

说明

样例树形状   
      1
    /    \
   2     3
         /
       4
         \
          5  

说明:本题目包含复杂数据结构TreeNode,点此查看相关信息
检查左右子树的高度差是否小于等于1即可
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 树的根节点
     * @return bool布尔型
     */
    public boolean isBalanced (TreeNode root) {
        // write code here
        if(root == null)
            return true;       // 空树也是平衡数
        else  // 否则计算左右子树的高度差是否<=1
            return Math.abs(treeDepth(root.left) - treeDepth(root.right)) <= 1;
    }
    
    private int treeDepth(TreeNode root) {
        if(root == null) return 0;
        int left = treeDepth(root.left);
        int right = treeDepth(root.right);
        return Math.max(left, right) + 1;
    }
}


发表于 2021-02-07 16:16:38 回复(0)
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
 
#
#
# @param root TreeNode类 树的根节点
# @return bool布尔型
#
class Solution:
    def isBalanced(self, root ):
        # write code here
        head=root
        nums=0
        dict1={}
        stack=[]
        stack.append(head)
        while stack:
            nextstack=[]
            nums+=1
            for i in stack:
                if i.left:
                    nextstack.append(i.left)
                if i.right:
                    nextstack.append(i.right)
                #将叶子节点加入字典,并记录层数,叶子节点在同一层字典长度为1
                if not i.left and not i.right and nums not in dict1:
                    dict1[nums]=i
            stack=nextstack
        if len(dict1)!=1:
            returnTrue
        else:
            returnFalse
发表于 2021-10-27 13:44:51 回复(0)