leetcode Balanced Binary Tree

来源:互联网 发布:千手观音知乎 编辑:程序博客网 时间:2024/06/11 14:43

题目链接这里

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private boolean balanced=true;    public boolean isBalanced(TreeNode root) {       real(root);       return balanced;       }    public int real(TreeNode root)    {        if(!balanced)        {            return -1;        }        if(root==null)        {            return 0;        }        int leftDeep=real(root.left);        int rightDeep=real(root.right);        if(Math.abs(leftDeep-rightDeep)>1)        {            balanced=false;            return -1;        }        else        {            return Math.max(leftDeep,rightDeep)+1;        }    }}
0 0
原创粉丝点击