leetcode 110 Balanced Binary Tree
来源:互联网 发布:linux内核调试方法 编辑:程序博客网 时间:2024/05/01 01:24
题目要求:判断一个二叉树是否为平衡二叉树(该二叉树的所有节点的左右子树高度差不能超过1)
tags:tree,depth-first search recursive
我的思路:
1.遍历所有的节点,获取其左右子树的高度
2.计算左右子树的高度差,如果有大于1的,则为非平衡二叉树,如果全部满足,则为平衡二叉树。
public boolean isBalanced(TreeNode root) { if(root==null){ return true; } int minus = treeHeight(root.left)-treeHeight(root.right); if(minus>=-1&&minus<=1){ return isBalanced(root.left)&&isBalanced(root.right); }else{ return false; } } public int treeHeight(TreeNode root){ if(root!=null){ return 1+Math.max(treeHeight(root.left),treeHeight(root.right)); }else{ return 0; } }
另一种思路:使用dfs
public boolean isBalanced2(TreeNode root){ return dfsHeight(root)!=-1; } public int dfsHeight(TreeNode root){ if(root==null){ return 0; } int leftHeight = dfsHeight(root.left); if(leftHeight==-1){ return -1; } int rightHeight = dfsHeight(root.right); if(rightHeight==-1){ return -1; } if(Math.abs(leftHeight-rightHeight)>1){ return -1; } return 1+Math.max(leftHeight, rightHeight); }
0 0
- LeetCode(110)Balanced Binary Tree
- LeetCode 110 Balanced Binary Tree
- LeetCode: Balanced Binary Tree [110]
- LeetCode 110 Balanced Binary Tree
- [leetcode 110] Balanced Binary Tree
- leetcode-110 Balanced Binary Tree
- leetCode #110 Balanced Binary Tree
- [LeetCode 110]Balanced Binary Tree
- leetcode || 110、Balanced Binary Tree
- Leetcode[110]-Balanced Binary Tree
- LeetCode 110 Balanced Binary Tree
- leetcode[110]:Balanced Binary Tree
- LeetCode(110) Balanced Binary Tree
- leetcode 110Balanced Binary Tree
- Leetcode# 110 Balanced Binary Tree
- leetcode 110: Balanced Binary Tree
- leetcode-110-Balanced Binary Tree
- LeetCode 110 : Balanced Binary Tree
- listbox
- 哔哩哔哩真实视频地址解析-初探
- hadoop datanode部分启动不了
- 动态规划算法学习
- 对QT namespace UI的理解
- leetcode 110 Balanced Binary Tree
- freescale:i.MX6ul平台—ext4文件系统挂载错误总结
- 从0开始<十三>:getint()函数(类似于scanf函数)以及库函数strncpy、strncat及strncmp函数的实现
- QT学习资料总结
- jquery操作checkbox,实现全选。
- Gson 源码分析 总结
- IOS网络笔记--(三方库)上拉加载下拉刷新
- SNN 未被启动异常
- python模块之codecs