zoukankan      html  css  js  c++  java
  • #树#判断平衡二叉树

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root == null) return true;
            height(root);
            return this.flag;
    
        }
        private boolean flag = true;
        // public int height(TreeNode h) {
        //     if(h==null) return 0;
        //     return 1+ Math.max(height(h.left), height(h.right));
        // }
        // public void dfs(TreeNode h) {
        //     if(h==null) return;
        //     if(flag==false) return;
        //     int left = height(h.left);
        //     int right = height(h.right);
            
        //     if(Math.abs(left-right)>1) {
        //         flag = false;
        //         return;
        //     }
        //     dfs(h.left);
        //     dfs(h.right);
        // }
    
        public int height(TreeNode h) {
            if(h == null || flag == false) return 0;
            int l = height(h.left)+1;
            int r = height(h.right)+1;
            if(Math.abs(l-r)>1) {
                flag = false;
            }
            return Math.max(l,r);
        }
    
    
    
    
    
    
    
    
    
    
    
    }
  • 相关阅读:
    pycharm过期后,修改hosts文件?
    三种格式化方式
    virtualenv安装及使用
    二分查找以及单例模式
    目录总览
    SQLAlchemy
    Redis
    linux 安装虚拟机
    shell基本命令
    Linux 命令大全
  • 原文地址:https://www.cnblogs.com/lyr-2000/p/13301697.html
Copyright © 2011-2022 走看看