题目一:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:
- 如果树只有一个节点,那么深度为1
- 如果树的根节点只有左子树,没有右子树,那么深度等于左子树的深度+1
- 如果树的根节点只有右子树,没有左子树,那么深度等于右子树的深度+1
- 如果树的根节点既有左子树又有右子树,那么深度等于max(left,right)+ 1
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if pRoot is None:
return 0
left = self.TreeDepth(pRoot.left)
right = self.TreeDepth(pRoot.right)
return max(left,right)+1
题目二
输入一棵二叉树,判断该二叉树是否是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它是一颗平衡二叉树。
思路一:
采用上一题计算深度的思路,调用TreeDepth得到左右子树的深度,判断其差值是否大于1 。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if pRoot is None:
return 0
left = self.TreeDepth(pRoot.left)
right = self.TreeDepth(pRoot.right)
return max(left,right)+1
def IsBalanced_Solution(self, pRoot):
# write code here
if pRoot is None:
return True
left = self.TreeDepth(pRoot.left)
right = self.TreeDepth(pRoot.right)
diff = abs(left-right)
if diff > 1:
return False
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
网友评论