首先是递归的方法
-
如果只有根节点,那就返回1
-
如果有左子树,没有右子树,那么树的深度就是左子树的深度+1。同理只有右子树的情况。
-
如果既有左子树,又有右子树,那么就是两个子树中较大的深度+1
def TreeDepth(self, pRoot): # write code here if not pRoot: return 0 left = self.TreeDepth(pRoot.left) right = self.TreeDepth(pRoot.right) return max(left,right) +1
34-平衡二叉树
之所以把这道题放在这,因为它用到了求树的深度的方法,当然该方法效率较低,多次判断树的深度,之后会有效率高的方法。
主要步骤为:
- 从根节点开始,判断它左子树和右子树的深度,判断他们相差是否大于1,是则返回False,否则继续
- 递归根节点的左子树,和右子树,然后继续判断即可
# -*- 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):
# write code here
if not pRoot:
return True
left = self.tree_d(pRoot.left)
right = self.tree_d(pRoot.right)
if abs(left-right)>1:
return False
return self.IsBalanced_Solution(pRoot.left)&self.IsBalanced_Solution(pRoot.right)
def tree_d(self,pRoot):
if not pRoot:
return 0
left = self.tree_d(pRoot.left)
right = self.tree_d(pRoot.right)
return max(left,right)+1
网友评论