LeetCode110.Balanced Binary Tree题解
来源:互联网 发布:plsql导出表数据dmp 编辑:程序博客网 时间:2024/06/08 02:28
1. 题目描述
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.
2. 分析
根据平衡二叉树(BST)的定义:给出一棵树的根节点,让我们判断这棵树是不是满足平衡二叉树的条件:即任意一个节点的左右子树的深度之差不大于1.
拿到题目,我的第一反应就是先设计一个求树的深度的函数,然后再对整棵树进行递归遍历,判断每个节点下面的左右子树深度之差,如果大于1的话,则为false。用了9ms过了226个测试样例,如下:
3. 源码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int getDepth(TreeNode* root) { if (root == NULL) { return 0; } int leftDepth = getDepth(root->left); int rightDepth = getDepth(root->right); if (leftDepth > rightDepth) { return leftDepth+1; } return rightDepth+1; } bool isBalanced(TreeNode* root) { if (root == NULL) { return true; } int leftDepth = getDepth(root->left); int rightDepth = getDepth(root->right); if (abs(leftDepth - rightDepth) <= 1) { if(isBalanced(root->left) == true && isBalanced(root->right) == true) { return true; } return false; } return false; }};
4. 心得
这是BST比较基础的题目,但是在做的时候还是交了3次才得到正确结果。2次失败的原因是:
4.1. 第1次失败
没有通过样例[1,2,2,3,null,null,3,4,null,null,4],这是因为我只考虑了根节点左右子树深度之差满足条件,而忘记了每一个节点都需要。
4.2. 第2次失败
没有通过样例[1,2,3,4,5,null,6,7,null,null,null,null,8],这是因为在设计返回值条件的时候只遍历了左子树,没有遍历右子树的情况。
0 0
- LeetCode110.Balanced Binary Tree题解
- LeetCode110 - Balanced Binary Tree
- LeetCode110-Balanced Binary Tree
- leetcode110---Balanced Binary Tree
- LeetCode110:Balanced Binary Tree
- LeetCode110. Balanced Binary Tree
- leetcode110~Balanced Binary Tree
- leetcode110. Balanced Binary Tree
- LeetCode110 Balanced Binary Tree
- leetcode110 Balanced Binary Tree
- Leetcode110. Balanced Binary Tree
- LeetCode110. Balanced Binary Tree
- LeetCode110—Balanced Binary Tree
- LeetCode110——Balanced Binary Tree
- LeetCode110 Blanced Binary Tree Java 题解
- LeetCode题解:Balanced Binary Tree
- LeetCode题解: Balanced Binary Tree
- leetcode Balanced Binary Tree 题解
- Java打印菱形
- kafka消息与同步机制
- MySQL的表类型的(存储引擎)的选择MyISAM+InnoDB+MEMORY+MERGE
- jvm知识点总览-高级Java工程师面试必备
- TCP/IP协议 <二>
- LeetCode110.Balanced Binary Tree题解
- jsp乱码问题全解
- LDR指令
- 渗透测试攻防练习实验室 (资源分享,国外在线教程)
- 用变量简化计算
- 解决fatal error: 'ffi.h' file not found
- 用户自动创建脚本
- 数据库MySQL的安装
- java中byte[]、buffer、string转换