判断平衡二叉树(JAVA)

来源:互联网 发布:爱情主演 网络歌手 编辑:程序博客网 时间:2024/05/23 12:34

解法一:递归次数少,代码量不多

public class Solution {    public boolean IsBalanced_Solution(TreeNode root) {       return getDepth(root) != -1;    }    public int getDepth(TreeNode node){        if(node == null) return 0;        int left = getDepth(node.left);        int right = getDepth(node.right);        if(left == -1) return -1;        if(right == -1) return -1;        return Math.abs(left-right)>1 ? -1 : Math.max(left,right)+1;    }}

解法二:代码量极少,但是递归次数多很多

public class Solution {    public boolean IsBalanced_Solution(TreeNode root) {        if(root == null) return true;        if(Math.abs(getDepth(root.right)-getDepth(root.left))>1) return false;        return IsBalanced_Solution(root.right) && IsBalanced_Solution(root.left);    }    public int getDepth(TreeNode node){        if(node == null) return 0;        return Math.max(getDepth(node.right)+1,getDepth(node.left)+1);    }}