LeetCode 110:Balanced Binary Tree(Java)

来源:互联网 发布:软件对比分析报告 编辑:程序博客网 时间:2024/06/10 09:10

思路是使用递归,要用到一个子问题就是求一棵二叉树的深度,也是递归的思想。

这种左右递归的格式对二叉树很有用,要掌握。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isBalanced(TreeNode root) {        if(root == null) return true;        //在此处判断可以防止程序在出现false情况后继续运行        if(!(Math.abs(maxDepth(root.left) - maxDepth(root.right)) < 2))            return false;        boolean left = isBalanced(root.left);        boolean right = isBalanced(root.right);        return left && right;    }    public int maxDepth(TreeNode root) {        if(root == null) return 0;        int l = maxDepth(root.left);        int r = maxDepth(root.right);        return l > r ? l + 1 : r + 1;    }}
0 0
原创粉丝点击