110. Balanced Binary Tree
是否平衡:每个节点的左右子树高度差小于1
求高度:后序遍历,从下往上,层层往上返回
求深度:前序遍历 ,从上往下,不需要返回结果
此处代码用后序遍历,只要有一个节点不是平衡就返回-1,之后所有上层节点都是-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 isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if self.getHeight(root)==-1:
return False
else:
return True
def getHeight(self, node):
if node is None:
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 1+max(leftHeight,rightHeight)
(学完回溯章节后再写)257. Binary Tree Paths
要用前序遍历(中左右):要让parent node指向child node
有递归就有回溯
中要写到终止条件(判断叶子节点)前,不然叶子节点就放不进去了
回溯有点不太明白
404. Sum of Left Leaves
左孩子不为null,但左孩子的左右孩子为null
后序遍历稍简洁
# 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 == None:
return 0
if root.left == None and root.right == None:
return 0
leftNum = self.sumOfLeftLeaves(root.left) #左
if root.left != None and root.left.left == None and root.left.right == None: #左子树是左叶子的情况
leftNum = root.left.val
rightNum = self.sumOfLeftLeaves(root.right) #右
s = leftNum + rightNum #中
return s