zoukankan      html  css  js  c++  java
  • 【18】平衡二叉树

    【题目】

    实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,其两颗子树的高度差不超过1。

    给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。

    【代码】

    import java.util.*;
    
    /*
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int val) {
            this.val = val;
        }
    }*/
    public class Balance {
        public boolean isBalance(TreeNode root) {
            if(root == null){
                return true;
            }
           int left = getDepth(root.left);
           int right = getDepth(root.right);
           int dif = left - right;
           if(dif < -1 || dif > 1){
               return false;
           }
           return  isBalance(root.left) && isBalance(root.right);
        }
        
        //获取任意结点的深度
        public int getDepth(TreeNode node){
            if (node == null){
                return 0;
            }
            
            int left = getDepth(node.left);
            int right = getDepth(node.right);
            return left > right ? left+1 : right+1;
        }
    }
  • 相关阅读:
    Men and women can't be 'just friends
    thin-provisioning-tools
    自签名证书
    sqlite manager
    python -m SimpleHTTPServer 80801
    rsa or dsa?
    sl4a
    mtp
    sl4a
    基站记录仪是个啥?
  • 原文地址:https://www.cnblogs.com/noaman/p/7066583.html
Copyright © 2011-2022 走看看