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
- 110.Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- struts2注解
- C++多线程记录1
- 使用整数类型处理货币
- Neural Networks and Deep Learning 学习笔记(一)
- 通过设置nginx的client_max_body_size解决nginx+php上传大文件的问题
- 110. Balanced Binary Tree
- Windows批处理编程
- 移动前端知识总结
- Android笔记之View XML属性自定义
- 基于tomcat 7.0.68 的websocket 实现,及通过 HttpSessionId 实现websocket session 共享
- 27. Remove Element
- 简单的android数据类和Json转换(Data Json)
- xml 和 Java Annotation 的优缺点对比
- 踩坑事件:windows操作系统下的eclipse中编写SparkSQL不能从本地读取或者保存parquet文件