[leetcode]Balanced Binary Tree

来源:互联网 发布:福州技术支持一九网络 编辑:程序博客网 时间:2024/06/05 22:57
<pre name="code" class="javascript">自己的解法可以减少递归调用的次数,通过flag标志先判断 是否要递归。
public class Solution {    boolean flag=true;    public boolean isBalanced(TreeNode root) {        if(root==null)            return true;        dep(root);        return flag;    }    public int dep(TreeNode root){        int ldep,rdep;        if(root==null)            return 0;        if(!flag)           return 0;        ldep=dep(root.left);        rdep=dep(root.right);        if(Math.abs(ldep-rdep)>1)            flag=false;        return Math.max(ldep,rdep)+1;        }}



0 0
原创粉丝点击