剑指Offer:平衡二叉树Java/Python
2019-05-06 10:07
225 查看
1.题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
2.算法描述
平衡二叉树是指每个结点的左右子树的高度之差不超过1的树。
利用二叉树的前序遍历\red{前序遍历}前序遍历,先判断根节点是否满足上述性质。然后判断左右子树是否满足上述性质。
3.代码描述
3.1.Java代码
public class Solution { public boolean IsBalanced_Solution(TreeNode root) { if(root == null) return true; int leftDepth = TreeDepth(root.left); int rightDepth = TreeDepth(root.right); if(leftDepth-rightDepth >= 2 || rightDepth-leftDepth >= 2) return false; return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right); } public int TreeDepth(TreeNode root) { if(root == null) return 0; int leftDepth = TreeDepth(root.left); int rightDepth = TreeDepth(root.right); return Math.max(leftDepth, rightDepth) + 1; } }
3.2.Python代码
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def IsBalanced_Solution(self, pRoot): if not pRoot: return True leftDepth = self.TreeDepth(pRoot.left) rightDepth = self.TreeDepth(pRoot.right) if abs(leftDepth-rightDepth)>=2: return False return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right) def TreeDepth(self, pRoot): if not pRoot: return 0 leftDepth = self.TreeDepth(pRoot.left) rightDepth = self.TreeDepth(pRoot.right) return max(leftDepth, rightDepth) + 1
相关文章推荐
- 剑指Offer:翻转单词顺序列Java/Python
- 剑指OFFER——判断一棵树是否是平衡二叉树 java实现
- 剑指Offer:孩子们的游戏(圆圈中最后剩下的数)Java/Python
- 剑指Offer:删除链表中重复的结点Java/Python
- 剑指Offer:序列化二叉树Java/Python
- 剑指Offer:表示数值的字符串Java/Python
- 剑指Offer:求1+2+3+...+n Java/Python
- 剑指Offer:滑动窗口的最大值Java/Python
- 剑指offer第一题和第二题(python版和java版)
- 剑指Offer:正则表达式匹配Java/Python
- 剑指Offer:字符流中第一个不重复的字符Java/Python
- 剑指offer:判断二叉树是不是平衡二叉树(java)
- 剑指Offer:按之字形顺序打印二叉树Java/Python
- 牛客:剑指offer:平衡二叉树 (Java)
- 剑指Offer:左旋转字符串Java/Python
- 剑指Offer:数组中重复的数字Java/Python
- 剑指Offer:链表中环的入口结点Java/Python
- 剑指Offer:机器人的运动范围Java/Python
- Java的不定长参数和Python的不定长参数对比
- C/Java/Python/Objective-C在OS X上的性能实验