110. Balanced Binary Tree

来源:互联网 发布:java面向对象思维导图 编辑:程序博客网 时间:2024/05/01 05:01

题目:https://leetcode.com/problems/balanced-binary-tree/

代码:

/** * 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(getdepth(root)<=2)            return true;        if(Math.abs(getdepth(root.left)-getdepth(root.right))<=1)            return isBalanced(root.left)&&isBalanced(root.right);        else            return false;    }    public int getdepth(TreeNode root)    {        if(root==null)            return 0;        return Math.max(getdepth(root.left),getdepth(root.right))+1;    }}3ms题意为判断是否为平衡二叉树平衡二叉树:平衡二叉树,又称AVL树。它或者是一棵空树,或者是具有下列性质的二叉树:它的左子树和右子树都是平衡二叉树,且左子树和右子树的高度之差之差的绝对值不超过1.。==================================================dicuss里面一个1ms的解法public class Solution {    public boolean isBalanced(TreeNode root) {        return checkBalance(root) == -1 ? false : true;    }    // 1. If a subtree is hit as unbalanced, the whole tree is unbalanced. In this case, -1 is set as the return value.    // 2. If the left subtree and the right subtree of a node are balanced, there are two more cases:    // 2.1. The tree rooted at the node is unbalanced (the depth of its two subtrees differs by more than 1), as a result, -1 is returned.    // 2.2 The tree rooted at the node is balanced, then the depth of the tree will be returned.    public int checkBalance(TreeNode node){        if (node == null) // case 2.2            return 0;        int left = checkBalance(node.left);        if (left == -1) // check case 1            return -1;        int right = checkBalance(node.right);        if (right == -1) // check case 1            return -1;        if (left - right > 1 || right - left > 1)            return -1; // check case 2.1        return (left > right ? left : right) + 1; // case 2.2    }}=======================================================分析:我用了两次递归,一个是求深度,一个是判断平衡二叉树1ms的这个方法只用了一次难道是这个的原因提升了2ms?
0 0
原创粉丝点击