赞
踩
思路:后序递归遍历左右子树,判断左右子树是否为平衡树,若左右子树高度差绝对值不超过1,则为平衡树
- # Definition for a binary tree node.
- # class TreeNode(object):
- # def __init__(self, val=0, left=None, right=None):
- # self.val = val
- # self.left = left
- # self.right = right
- class Solution(object):
- def getHeight(self,node):
- if not node:
- return 0
- leftHeight=self.getHeight(node.left)
- if leftHeight==-1:return -1
- rightHeight=self.getHeight(node.right)
- if rightHeight==-1:return -1
-
- if abs(leftHeight-rightHeight)>1:
- return -1
- else:
- return max(leftHeight,rightHeight)+1
- def isBalanced(self, root):
- """
- :type root: TreeNode
- :rtype: bool
- """
- if self.getHeight(root)==-1:
- return False
- else:
- return True
思路:递归加回溯。
- # Definition for a binary tree node.
- # class TreeNode(object):
- # def __init__(self, val=0, left=None, right=None):
- # self.val = val
- # self.left = left
- # self.right = right
- class Solution(object):
- def travelback(self,cur,path,result):
- path.append(cur.val)
- if cur.left is None and cur.right is None:
- spath='->'.join(map(str,path))
- result.append(spath)
- return
- if cur.left:
- self.travelback(cur.left,path,result)
- path.pop()
- if cur.right:
- self.travelback(cur.right,path,result)
- path.pop()
-
-
- def binaryTreePaths(self, root):
- """
- :type root: TreeNode
- :rtype: List[str]
- """
- path=[]
- result=[]
- if not root:
- return result
- self.travelback(root,path,result)
- return result
-
思路:左叶子之和,左子树左叶子之和加右子树左叶子之和
- # Definition for a binary tree node.
- # class TreeNode(object):
- # def __init__(self, val=0, left=None, right=None):
- # self.val = val
- # self.left = left
- # self.right = right
- class Solution(object):
- def sumOfLeftLeaves(self, root):
- """
- :type root: TreeNode
- :rtype: int
- """
- if root is None:
- return 0
- if root.left is None and root.right is None:
- return 0
- leftValue=self.sumOfLeftLeaves(root.left)
- if root.left is not None and root.left.left is None and root.left.right is None:
- leftValue=root.left.val
- rightVaue=self.sumOfLeftLeaves(root.right)
- return leftValue+rightVaue
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。