zoukankan      html  css  js  c++  java
  • 39、平衡二叉树

    输入一棵二叉树,判断该二叉树是否是平衡二叉树
    在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
    ===========Python===========
    # -*- coding:utf-8 -*-
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution:
        def IsBalanced_Solution(self, pRoot):
            # write code here
            if not pRoot:
                return True
            return abs(self.depth(pRoot.left) - self.depth(pRoot.right)) <= 1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
        def depth(self, root):
            if not root:
                return 0
            return max(self.depth(root.left),self.depth(root.right)) + 1

    ================Java===============

    public class Solution {
        public boolean IsBalanced_Solution(TreeNode root) {
            if (root == null) {
                return true;
            }
            return Math.abs(depth(root.left) - depth(root.right)) <= 1 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
        }
        
        public int depth(TreeNode p) {
            if (p == null) {
                return 0;
            }
            return Math.max(depth(p.left), depth(p.right)) + 1;
        }
    }
  • 相关阅读:
    js-artDialog文档说明
    T-SQL数据库函数
    强大的Jquery对象选择器
    学习正则表达式
    经典正则
    其他常用的正则表达式
    celery的使用
    django中间件
    AJAX
    Django Form表单组件
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13539395.html
Copyright © 2011-2022 走看看