• #树#判断平衡二叉树


    /**
     * 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);
        }
    
    
    
    
    
    
    
    
    
    
    
    }
  • 相关阅读:
    CF-807B
    CF-807A
    sort()的升降序函数操作
    CF-805D
    CF-805B
    CF-805A
    CF-796C
    CF-796B
    图论学习四之Disjoint set union并查集
    图论学习三之Shortest Path最短路
  • 原文地址:https://www.cnblogs.com/lyr-2000/p/13301697.html
Copyright © 2020-2023  润新知