leetcode 110 平衡二叉树

简介

使用递归判断是否是平衡二叉树

code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean b;
    int dfs(TreeNode root, int level){
        if(root == null){
            return level;
        }
        int left = dfs(root.left, level+1);
        int right = dfs(root.right, level+1);
        if(Math.abs(left - right) > 1) b = false;
        return Math.max(left, right);
    }
    public boolean isBalanced(TreeNode root) {
        b = true;
        dfs(root, 0);
        return b;
    }
}
上一篇:【Ybtoj 第19章例3】宝物筛选【背包问题】


下一篇:7-110 求符合给定条件的整数集 (15分)