110. Balanced Binary Tree
来源:互联网 发布:淘宝号怎么养 编辑:程序博客网 时间:2024/06/06 07:12
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
判断一棵树是否平衡
因为平衡的定义就是左右子树的高度差不超过1 所以要求高度
很直接的想法就是从根节点到叶子节点 逐个求左右高度 然后判断是否是平衡的
class solution {public: int depth (TreeNode *root) { if (root == NULL) return 0; return max (depth(root -> left), depth (root -> right)) + 1; } bool isBalanced (TreeNode *root) { if (root == NULL) return true; int left=depth(root->left); int right=depth(root->right); return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right); }};
但是这个过程中有大量重复计算 比如输入是
1
2 3
4 5 6 7
在判断1是否平衡时 求2的高的同时 也求了4,5的高度
但是之后判断2是否平衡 还会计算4,5的高度
所以要修改成先求叶子节点是否平衡 然后向上传递高度 所以需要设定一个返回值 同时包含子树是否平衡 又包含子树高度的信息
实际上 我们只需要能区分开平衡和高度就可以了
int就够了 当不平衡时返回-1 高度是不可能为负数的
public boolean isBalanced(TreeNode root) { return getDepth(root) != -1; } private int getDepth(TreeNode root) { if (root == null) return 0; int left = getDepth(root.left); if (left == -1) return -1; int right = getDepth(root.right); if (right == -1) return -1; if (Math.abs(left-right) > 1) return -1; return Math.max(left, right) + 1; }
另外 getDepth可以写作
private int getDepth(TreeNode root) { if (root == null) return 0; int left = getDepth(root.left); int right = getDepth(root.right); if (left == -1 || right == -1 || Math.abs(left-right) > 1) return -1; return Math.max(left, right) + 1; }
看上去会简洁一些 但实际上会增加计算量 比如 对于第一种写法 对于左子树不平衡的情况 是不需要求右子树的深度的
但是第二种写法 会求右子树的深度 所以第一种写法的效率高一些 相当于是失败快速返回的原则
直接写出了最优解 看了8个月之前的提交记录 提升不少
阅读全文
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
- 【linux】 su,su -,和sudo的区别
- Pycharm 激活(JetBrains IDEA 系列产品通用激活方法)持续收集~
- hbase初识---开始认识hbase
- Java Socket以及界面动态加载的简单使用
- JAVA 上加密算法的实现用例 MD5/SHA1,DSA,DESede/DES,Diffie-Hellman 的使用
- 110. Balanced Binary Tree
- 透彻的掌握 Spring 中@transactional 的使用
- 吴恩达深度学习第一课第四周课后作业1参考
- java--反射
- geohash原理浅析
- 设计模式——状态模式
- 682. Baseball Game
- win10--L2TP教程
- Java中的经典算法之冒泡排序(Bubble Sort)